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-2014, 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/blkdev.h>
47 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
50 /* UIC command timeout, unit: ms */
51 #define UIC_CMD_TIMEOUT 500
53 /* NOP OUT retries waiting for NOP IN response */
54 #define NOP_OUT_RETRIES 10
55 /* Timeout after 30 msecs if NOP OUT hangs without response */
56 #define NOP_OUT_TIMEOUT 30 /* msecs */
58 /* Query request retries */
59 #define QUERY_REQ_RETRIES 10
60 /* Query request timeout */
61 #define QUERY_REQ_TIMEOUT 30 /* msec */
63 /* Task management command timeout */
64 #define TM_CMD_TIMEOUT 100 /* msecs */
66 /* maximum number of link-startup retries */
67 #define DME_LINKSTARTUP_RETRIES 3
69 /* maximum number of reset retries before giving up */
70 #define MAX_HOST_RESET_RETRIES 5
72 /* Expose the flag value from utp_upiu_query.value */
73 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
75 /* Interrupt aggregation default timeout, unit: 40us */
76 #define INT_AGGR_DEF_TO 0x02
78 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
82 _ret = ufshcd_enable_vreg(_dev, _vreg); \
84 _ret = ufshcd_disable_vreg(_dev, _vreg); \
88 static u32 ufs_query_desc_max_size[] = {
89 QUERY_DESC_DEVICE_MAX_SIZE,
90 QUERY_DESC_CONFIGURAION_MAX_SIZE,
91 QUERY_DESC_UNIT_MAX_SIZE,
92 QUERY_DESC_RFU_MAX_SIZE,
93 QUERY_DESC_INTERCONNECT_MAX_SIZE,
94 QUERY_DESC_STRING_MAX_SIZE,
95 QUERY_DESC_RFU_MAX_SIZE,
96 QUERY_DESC_GEOMETRY_MAZ_SIZE,
97 QUERY_DESC_POWER_MAX_SIZE,
98 QUERY_DESC_RFU_MAX_SIZE,
102 UFSHCD_MAX_CHANNEL = 0,
104 UFSHCD_CMD_PER_LUN = 32,
105 UFSHCD_CAN_QUEUE = 32,
112 UFSHCD_STATE_OPERATIONAL,
115 /* UFSHCD error handling flags */
117 UFSHCD_EH_IN_PROGRESS = (1 << 0),
120 /* UFSHCD UIC layer error flags */
122 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
123 UFSHCD_UIC_NL_ERROR = (1 << 1), /* Network layer error */
124 UFSHCD_UIC_TL_ERROR = (1 << 2), /* Transport Layer error */
125 UFSHCD_UIC_DME_ERROR = (1 << 3), /* DME error */
128 /* Interrupt configuration options */
135 #define ufshcd_set_eh_in_progress(h) \
136 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
137 #define ufshcd_eh_in_progress(h) \
138 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
139 #define ufshcd_clear_eh_in_progress(h) \
140 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
142 #define ufshcd_set_ufs_dev_active(h) \
143 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
144 #define ufshcd_set_ufs_dev_sleep(h) \
145 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
146 #define ufshcd_set_ufs_dev_poweroff(h) \
147 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
148 #define ufshcd_is_ufs_dev_active(h) \
149 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
150 #define ufshcd_is_ufs_dev_sleep(h) \
151 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
152 #define ufshcd_is_ufs_dev_poweroff(h) \
153 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
155 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
156 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
157 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
158 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
159 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
160 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
161 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
164 static inline enum ufs_dev_pwr_mode
165 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
167 return ufs_pm_lvl_states[lvl].dev_state;
170 static inline enum uic_link_state
171 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
173 return ufs_pm_lvl_states[lvl].link_state;
176 static void ufshcd_tmc_handler(struct ufs_hba *hba);
177 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
178 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
179 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
180 static void ufshcd_hba_exit(struct ufs_hba *hba);
181 static int ufshcd_probe_hba(struct ufs_hba *hba);
182 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
184 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
185 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
186 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
187 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
188 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
189 static irqreturn_t ufshcd_intr(int irq, void *__hba);
190 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
191 struct ufs_pa_layer_attr *desired_pwr_mode);
192 static int ufshcd_change_power_mode(struct ufs_hba *hba,
193 struct ufs_pa_layer_attr *pwr_mode);
195 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
199 if (!hba->is_irq_enabled) {
200 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
203 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
205 hba->is_irq_enabled = true;
211 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
213 if (hba->is_irq_enabled) {
214 free_irq(hba->irq, hba);
215 hba->is_irq_enabled = false;
220 * ufshcd_wait_for_register - wait for register value to change
221 * @hba - per-adapter interface
222 * @reg - mmio register offset
223 * @mask - mask to apply to read register value
224 * @val - wait condition
225 * @interval_us - polling interval in microsecs
226 * @timeout_ms - timeout in millisecs
228 * Returns -ETIMEDOUT on error, zero on success
230 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
231 u32 val, unsigned long interval_us, unsigned long timeout_ms)
234 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
236 /* ignore bits that we don't intend to wait on */
239 while ((ufshcd_readl(hba, reg) & mask) != val) {
240 /* wakeup within 50us of expiry */
241 usleep_range(interval_us, interval_us + 50);
243 if (time_after(jiffies, timeout)) {
244 if ((ufshcd_readl(hba, reg) & mask) != val)
254 * ufshcd_get_intr_mask - Get the interrupt bit mask
255 * @hba - Pointer to adapter instance
257 * Returns interrupt bit mask per version
259 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
261 if (hba->ufs_version == UFSHCI_VERSION_10)
262 return INTERRUPT_MASK_ALL_VER_10;
264 return INTERRUPT_MASK_ALL_VER_11;
268 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
269 * @hba - Pointer to adapter instance
271 * Returns UFSHCI version supported by the controller
273 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
275 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
276 return ufshcd_vops_get_ufs_hci_version(hba);
278 return ufshcd_readl(hba, REG_UFS_VERSION);
282 * ufshcd_is_device_present - Check if any device connected to
283 * the host controller
284 * @hba: pointer to adapter instance
286 * Returns 1 if device present, 0 if no device detected
288 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
290 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
291 DEVICE_PRESENT) ? 1 : 0;
295 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
296 * @lrb: pointer to local command reference block
298 * This function is used to get the OCS field from UTRD
299 * Returns the OCS field in the UTRD
301 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
303 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
307 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
308 * @task_req_descp: pointer to utp_task_req_desc structure
310 * This function is used to get the OCS field from UTMRD
311 * Returns the OCS field in the UTMRD
314 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
316 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
320 * ufshcd_get_tm_free_slot - get a free slot for task management request
321 * @hba: per adapter instance
322 * @free_slot: pointer to variable with available slot value
324 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
325 * Returns 0 if free slot is not available, else return 1 with tag value
328 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
337 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
338 if (tag >= hba->nutmrs)
340 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
348 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
350 clear_bit_unlock(slot, &hba->tm_slots_in_use);
354 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
355 * @hba: per adapter instance
356 * @pos: position of the bit to be cleared
358 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
360 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
364 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
365 * @reg: Register value of host controller status
367 * Returns integer, 0 on Success and positive value if failed
369 static inline int ufshcd_get_lists_status(u32 reg)
372 * The mask 0xFF is for the following HCS register bits
382 return (((reg) & (0xFF)) >> 1) ^ (0x07);
386 * ufshcd_get_uic_cmd_result - Get the UIC command result
387 * @hba: Pointer to adapter instance
389 * This function gets the result of UIC command completion
390 * Returns 0 on success, non zero value on error
392 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
394 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
395 MASK_UIC_COMMAND_RESULT;
399 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
400 * @hba: Pointer to adapter instance
402 * This function gets UIC command argument3
403 * Returns 0 on success, non zero value on error
405 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
407 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
411 * ufshcd_get_req_rsp - returns the TR response transaction type
412 * @ucd_rsp_ptr: pointer to response UPIU
415 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
417 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
421 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
422 * @ucd_rsp_ptr: pointer to response UPIU
424 * This function gets the response status and scsi_status from response UPIU
425 * Returns the response result code.
428 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
430 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
434 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
436 * @ucd_rsp_ptr: pointer to response UPIU
438 * Return the data segment length.
440 static inline unsigned int
441 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
443 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
444 MASK_RSP_UPIU_DATA_SEG_LEN;
448 * ufshcd_is_exception_event - Check if the device raised an exception event
449 * @ucd_rsp_ptr: pointer to response UPIU
451 * The function checks if the device raised an exception event indicated in
452 * the Device Information field of response UPIU.
454 * Returns true if exception is raised, false otherwise.
456 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
458 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
459 MASK_RSP_EXCEPTION_EVENT ? true : false;
463 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
464 * @hba: per adapter instance
467 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
469 ufshcd_writel(hba, INT_AGGR_ENABLE |
470 INT_AGGR_COUNTER_AND_TIMER_RESET,
471 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
475 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
476 * @hba: per adapter instance
477 * @cnt: Interrupt aggregation counter threshold
478 * @tmout: Interrupt aggregation timeout value
481 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
483 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
484 INT_AGGR_COUNTER_THLD_VAL(cnt) |
485 INT_AGGR_TIMEOUT_VAL(tmout),
486 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
490 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
491 * @hba: per adapter instance
493 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
495 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
499 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
500 * When run-stop registers are set to 1, it indicates the
501 * host controller that it can process the requests
502 * @hba: per adapter instance
504 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
506 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
507 REG_UTP_TASK_REQ_LIST_RUN_STOP);
508 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
509 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
513 * ufshcd_hba_start - Start controller initialization sequence
514 * @hba: per adapter instance
516 static inline void ufshcd_hba_start(struct ufs_hba *hba)
518 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
522 * ufshcd_is_hba_active - Get controller state
523 * @hba: per adapter instance
525 * Returns zero if controller is active, 1 otherwise
527 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
529 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
532 static void ufshcd_ungate_work(struct work_struct *work)
536 struct ufs_hba *hba = container_of(work, struct ufs_hba,
537 clk_gating.ungate_work);
539 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
541 spin_lock_irqsave(hba->host->host_lock, flags);
542 if (hba->clk_gating.state == CLKS_ON) {
543 spin_unlock_irqrestore(hba->host->host_lock, flags);
547 spin_unlock_irqrestore(hba->host->host_lock, flags);
548 ufshcd_setup_clocks(hba, true);
550 /* Exit from hibern8 */
551 if (ufshcd_can_hibern8_during_gating(hba)) {
552 /* Prevent gating in this path */
553 hba->clk_gating.is_suspended = true;
554 if (ufshcd_is_link_hibern8(hba)) {
555 ret = ufshcd_uic_hibern8_exit(hba);
557 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
560 ufshcd_set_link_active(hba);
562 hba->clk_gating.is_suspended = false;
565 if (ufshcd_is_clkscaling_enabled(hba))
566 devfreq_resume_device(hba->devfreq);
567 scsi_unblock_requests(hba->host);
571 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
572 * Also, exit from hibern8 mode and set the link as active.
573 * @hba: per adapter instance
574 * @async: This indicates whether caller should ungate clocks asynchronously.
576 int ufshcd_hold(struct ufs_hba *hba, bool async)
581 if (!ufshcd_is_clkgating_allowed(hba))
583 spin_lock_irqsave(hba->host->host_lock, flags);
584 hba->clk_gating.active_reqs++;
587 switch (hba->clk_gating.state) {
591 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
592 hba->clk_gating.state = CLKS_ON;
596 * If we here, it means gating work is either done or
597 * currently running. Hence, fall through to cancel gating
598 * work and to enable clocks.
601 scsi_block_requests(hba->host);
602 hba->clk_gating.state = REQ_CLKS_ON;
603 schedule_work(&hba->clk_gating.ungate_work);
605 * fall through to check if we should wait for this
606 * work to be done or not.
611 hba->clk_gating.active_reqs--;
615 spin_unlock_irqrestore(hba->host->host_lock, flags);
616 flush_work(&hba->clk_gating.ungate_work);
617 /* Make sure state is CLKS_ON before returning */
618 spin_lock_irqsave(hba->host->host_lock, flags);
621 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
622 __func__, hba->clk_gating.state);
625 spin_unlock_irqrestore(hba->host->host_lock, flags);
629 EXPORT_SYMBOL_GPL(ufshcd_hold);
631 static void ufshcd_gate_work(struct work_struct *work)
633 struct ufs_hba *hba = container_of(work, struct ufs_hba,
634 clk_gating.gate_work.work);
637 spin_lock_irqsave(hba->host->host_lock, flags);
638 if (hba->clk_gating.is_suspended) {
639 hba->clk_gating.state = CLKS_ON;
643 if (hba->clk_gating.active_reqs
644 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
645 || hba->lrb_in_use || hba->outstanding_tasks
646 || hba->active_uic_cmd || hba->uic_async_done)
649 spin_unlock_irqrestore(hba->host->host_lock, flags);
651 /* put the link into hibern8 mode before turning off clocks */
652 if (ufshcd_can_hibern8_during_gating(hba)) {
653 if (ufshcd_uic_hibern8_enter(hba)) {
654 hba->clk_gating.state = CLKS_ON;
657 ufshcd_set_link_hibern8(hba);
660 if (ufshcd_is_clkscaling_enabled(hba)) {
661 devfreq_suspend_device(hba->devfreq);
662 hba->clk_scaling.window_start_t = 0;
665 if (!ufshcd_is_link_active(hba))
666 ufshcd_setup_clocks(hba, false);
668 /* If link is active, device ref_clk can't be switched off */
669 __ufshcd_setup_clocks(hba, false, true);
672 * In case you are here to cancel this work the gating state
673 * would be marked as REQ_CLKS_ON. In this case keep the state
674 * as REQ_CLKS_ON which would anyway imply that clocks are off
675 * and a request to turn them on is pending. By doing this way,
676 * we keep the state machine in tact and this would ultimately
677 * prevent from doing cancel work multiple times when there are
678 * new requests arriving before the current cancel work is done.
680 spin_lock_irqsave(hba->host->host_lock, flags);
681 if (hba->clk_gating.state == REQ_CLKS_OFF)
682 hba->clk_gating.state = CLKS_OFF;
685 spin_unlock_irqrestore(hba->host->host_lock, flags);
690 /* host lock must be held before calling this variant */
691 static void __ufshcd_release(struct ufs_hba *hba)
693 if (!ufshcd_is_clkgating_allowed(hba))
696 hba->clk_gating.active_reqs--;
698 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
699 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
700 || hba->lrb_in_use || hba->outstanding_tasks
701 || hba->active_uic_cmd || hba->uic_async_done)
704 hba->clk_gating.state = REQ_CLKS_OFF;
705 schedule_delayed_work(&hba->clk_gating.gate_work,
706 msecs_to_jiffies(hba->clk_gating.delay_ms));
709 void ufshcd_release(struct ufs_hba *hba)
713 spin_lock_irqsave(hba->host->host_lock, flags);
714 __ufshcd_release(hba);
715 spin_unlock_irqrestore(hba->host->host_lock, flags);
717 EXPORT_SYMBOL_GPL(ufshcd_release);
719 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
720 struct device_attribute *attr, char *buf)
722 struct ufs_hba *hba = dev_get_drvdata(dev);
724 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
727 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
728 struct device_attribute *attr, const char *buf, size_t count)
730 struct ufs_hba *hba = dev_get_drvdata(dev);
731 unsigned long flags, value;
733 if (kstrtoul(buf, 0, &value))
736 spin_lock_irqsave(hba->host->host_lock, flags);
737 hba->clk_gating.delay_ms = value;
738 spin_unlock_irqrestore(hba->host->host_lock, flags);
742 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
744 if (!ufshcd_is_clkgating_allowed(hba))
747 hba->clk_gating.delay_ms = 150;
748 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
749 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
751 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
752 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
753 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
754 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
755 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
756 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
757 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
760 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
762 if (!ufshcd_is_clkgating_allowed(hba))
764 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
765 cancel_work_sync(&hba->clk_gating.ungate_work);
766 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
769 /* Must be called with host lock acquired */
770 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
772 if (!ufshcd_is_clkscaling_enabled(hba))
775 if (!hba->clk_scaling.is_busy_started) {
776 hba->clk_scaling.busy_start_t = ktime_get();
777 hba->clk_scaling.is_busy_started = true;
781 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
783 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
785 if (!ufshcd_is_clkscaling_enabled(hba))
788 if (!hba->outstanding_reqs && scaling->is_busy_started) {
789 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
790 scaling->busy_start_t));
791 scaling->busy_start_t = ktime_set(0, 0);
792 scaling->is_busy_started = false;
796 * ufshcd_send_command - Send SCSI or device management commands
797 * @hba: per adapter instance
798 * @task_tag: Task tag of the command
801 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
803 ufshcd_clk_scaling_start_busy(hba);
804 __set_bit(task_tag, &hba->outstanding_reqs);
805 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
809 * ufshcd_copy_sense_data - Copy sense data in case of check condition
810 * @lrb - pointer to local reference block
812 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
815 if (lrbp->sense_buffer &&
816 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
817 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
818 memcpy(lrbp->sense_buffer,
819 lrbp->ucd_rsp_ptr->sr.sense_data,
820 min_t(int, len, SCSI_SENSE_BUFFERSIZE));
825 * ufshcd_copy_query_response() - Copy the Query Response and the data
827 * @hba: per adapter instance
828 * @lrb - pointer to local reference block
831 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
833 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
835 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
837 /* Get the descriptor */
838 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
839 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
840 GENERAL_UPIU_REQUEST_SIZE;
844 /* data segment length */
845 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
846 MASK_QUERY_DATA_SEG_LEN;
847 buf_len = be16_to_cpu(
848 hba->dev_cmd.query.request.upiu_req.length);
849 if (likely(buf_len >= resp_len)) {
850 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
853 "%s: Response size is bigger than buffer",
863 * ufshcd_hba_capabilities - Read controller capabilities
864 * @hba: per adapter instance
866 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
868 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
870 /* nutrs and nutmrs are 0 based values */
871 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
873 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
877 * ufshcd_ready_for_uic_cmd - Check if controller is ready
878 * to accept UIC commands
879 * @hba: per adapter instance
880 * Return true on success, else false
882 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
884 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
891 * ufshcd_get_upmcrs - Get the power mode change request status
892 * @hba: Pointer to adapter instance
894 * This function gets the UPMCRS field of HCS register
895 * Returns value of UPMCRS field
897 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
899 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
903 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
904 * @hba: per adapter instance
905 * @uic_cmd: UIC command
907 * Mutex must be held.
910 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
912 WARN_ON(hba->active_uic_cmd);
914 hba->active_uic_cmd = uic_cmd;
917 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
918 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
919 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
922 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
927 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
928 * @hba: per adapter instance
929 * @uic_command: UIC command
931 * Must be called with mutex held.
932 * Returns 0 only if success.
935 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
940 if (wait_for_completion_timeout(&uic_cmd->done,
941 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
942 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
946 spin_lock_irqsave(hba->host->host_lock, flags);
947 hba->active_uic_cmd = NULL;
948 spin_unlock_irqrestore(hba->host->host_lock, flags);
954 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
955 * @hba: per adapter instance
956 * @uic_cmd: UIC command
958 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
959 * with mutex held and host_lock locked.
960 * Returns 0 only if success.
963 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
965 if (!ufshcd_ready_for_uic_cmd(hba)) {
967 "Controller not ready to accept UIC commands\n");
971 init_completion(&uic_cmd->done);
973 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
979 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
980 * @hba: per adapter instance
981 * @uic_cmd: UIC command
983 * Returns 0 only if success.
986 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
991 ufshcd_hold(hba, false);
992 mutex_lock(&hba->uic_cmd_mutex);
993 ufshcd_add_delay_before_dme_cmd(hba);
995 spin_lock_irqsave(hba->host->host_lock, flags);
996 ret = __ufshcd_send_uic_cmd(hba, uic_cmd);
997 spin_unlock_irqrestore(hba->host->host_lock, flags);
999 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1001 mutex_unlock(&hba->uic_cmd_mutex);
1003 ufshcd_release(hba);
1008 * ufshcd_map_sg - Map scatter-gather list to prdt
1009 * @lrbp - pointer to local reference block
1011 * Returns 0 in case of success, non-zero value in case of failure
1013 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1015 struct ufshcd_sg_entry *prd_table;
1016 struct scatterlist *sg;
1017 struct scsi_cmnd *cmd;
1022 sg_segments = scsi_dma_map(cmd);
1023 if (sg_segments < 0)
1027 lrbp->utr_descriptor_ptr->prd_table_length =
1028 cpu_to_le16((u16) (sg_segments));
1030 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1032 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1034 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1035 prd_table[i].base_addr =
1036 cpu_to_le32(lower_32_bits(sg->dma_address));
1037 prd_table[i].upper_addr =
1038 cpu_to_le32(upper_32_bits(sg->dma_address));
1041 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1048 * ufshcd_enable_intr - enable interrupts
1049 * @hba: per adapter instance
1050 * @intrs: interrupt bits
1052 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1054 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1056 if (hba->ufs_version == UFSHCI_VERSION_10) {
1058 rw = set & INTERRUPT_MASK_RW_VER_10;
1059 set = rw | ((set ^ intrs) & intrs);
1064 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1068 * ufshcd_disable_intr - disable interrupts
1069 * @hba: per adapter instance
1070 * @intrs: interrupt bits
1072 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1074 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1076 if (hba->ufs_version == UFSHCI_VERSION_10) {
1078 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1079 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1080 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1086 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1090 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1091 * descriptor according to request
1092 * @lrbp: pointer to local reference block
1093 * @upiu_flags: flags required in the header
1094 * @cmd_dir: requests data direction
1096 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1097 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1099 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1103 if (cmd_dir == DMA_FROM_DEVICE) {
1104 data_direction = UTP_DEVICE_TO_HOST;
1105 *upiu_flags = UPIU_CMD_FLAGS_READ;
1106 } else if (cmd_dir == DMA_TO_DEVICE) {
1107 data_direction = UTP_HOST_TO_DEVICE;
1108 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1110 data_direction = UTP_NO_DATA_TRANSFER;
1111 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1114 dword_0 = data_direction | (lrbp->command_type
1115 << UPIU_COMMAND_TYPE_OFFSET);
1117 dword_0 |= UTP_REQ_DESC_INT_CMD;
1119 /* Transfer request descriptor header fields */
1120 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1123 * assigning invalid value for command status. Controller
1124 * updates OCS on command completion, with the command
1127 req_desc->header.dword_2 =
1128 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1132 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1134 * @lrbp - local reference block pointer
1135 * @upiu_flags - flags
1138 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1140 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1142 /* command descriptor fields */
1143 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1144 UPIU_TRANSACTION_COMMAND, upiu_flags,
1145 lrbp->lun, lrbp->task_tag);
1146 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1147 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1149 /* Total EHS length and Data segment length will be zero */
1150 ucd_req_ptr->header.dword_2 = 0;
1152 ucd_req_ptr->sc.exp_data_transfer_len =
1153 cpu_to_be32(lrbp->cmd->sdb.length);
1155 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd,
1156 (min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE)));
1160 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1163 * @lrbp: local reference block pointer
1164 * @upiu_flags: flags
1166 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1167 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1169 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1170 struct ufs_query *query = &hba->dev_cmd.query;
1171 u16 len = be16_to_cpu(query->request.upiu_req.length);
1172 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1174 /* Query request header */
1175 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1176 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1177 lrbp->lun, lrbp->task_tag);
1178 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1179 0, query->request.query_func, 0, 0);
1181 /* Data segment length */
1182 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1183 0, 0, len >> 8, (u8)len);
1185 /* Copy the Query Request buffer as is */
1186 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1189 /* Copy the Descriptor */
1190 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1191 memcpy(descp, query->descriptor, len);
1195 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1197 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1199 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1201 /* command descriptor fields */
1202 ucd_req_ptr->header.dword_0 =
1204 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1208 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
1209 * @hba - per adapter instance
1210 * @lrb - pointer to local reference block
1212 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1217 switch (lrbp->command_type) {
1218 case UTP_CMD_TYPE_SCSI:
1219 if (likely(lrbp->cmd)) {
1220 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1221 lrbp->cmd->sc_data_direction);
1222 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1227 case UTP_CMD_TYPE_DEV_MANAGE:
1228 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1229 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1230 ufshcd_prepare_utp_query_req_upiu(
1231 hba, lrbp, upiu_flags);
1232 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1233 ufshcd_prepare_utp_nop_upiu(lrbp);
1237 case UTP_CMD_TYPE_UFS:
1238 /* For UFS native command implementation */
1240 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1245 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1246 __func__, lrbp->command_type);
1248 } /* end of switch */
1254 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1255 * @scsi_lun: scsi LUN id
1257 * Returns UPIU LUN id
1259 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1261 if (scsi_is_wlun(scsi_lun))
1262 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1265 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1269 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1270 * @scsi_lun: UPIU W-LUN id
1272 * Returns SCSI W-LUN id
1274 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1276 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1280 * ufshcd_queuecommand - main entry point for SCSI requests
1281 * @cmd: command from SCSI Midlayer
1282 * @done: call back function
1284 * Returns 0 for success, non-zero in case of failure
1286 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1288 struct ufshcd_lrb *lrbp;
1289 struct ufs_hba *hba;
1290 unsigned long flags;
1294 hba = shost_priv(host);
1296 tag = cmd->request->tag;
1298 spin_lock_irqsave(hba->host->host_lock, flags);
1299 switch (hba->ufshcd_state) {
1300 case UFSHCD_STATE_OPERATIONAL:
1302 case UFSHCD_STATE_RESET:
1303 err = SCSI_MLQUEUE_HOST_BUSY;
1305 case UFSHCD_STATE_ERROR:
1306 set_host_byte(cmd, DID_ERROR);
1307 cmd->scsi_done(cmd);
1310 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1311 __func__, hba->ufshcd_state);
1312 set_host_byte(cmd, DID_BAD_TARGET);
1313 cmd->scsi_done(cmd);
1316 spin_unlock_irqrestore(hba->host->host_lock, flags);
1318 /* acquire the tag to make sure device cmds don't use it */
1319 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1321 * Dev manage command in progress, requeue the command.
1322 * Requeuing the command helps in cases where the request *may*
1323 * find different tag instead of waiting for dev manage command
1326 err = SCSI_MLQUEUE_HOST_BUSY;
1330 err = ufshcd_hold(hba, true);
1332 err = SCSI_MLQUEUE_HOST_BUSY;
1333 clear_bit_unlock(tag, &hba->lrb_in_use);
1337 /* IO svc time latency histogram */
1338 if (hba != NULL && cmd->request != NULL) {
1339 if (hba->latency_hist_enabled &&
1340 (cmd->request->cmd_type == REQ_TYPE_FS)) {
1341 cmd->request->lat_hist_io_start = ktime_get();
1342 cmd->request->lat_hist_enabled = 1;
1344 cmd->request->lat_hist_enabled = 0;
1347 WARN_ON(hba->clk_gating.state != CLKS_ON);
1349 lrbp = &hba->lrb[tag];
1353 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1354 lrbp->sense_buffer = cmd->sense_buffer;
1355 lrbp->task_tag = tag;
1356 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1357 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1358 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1360 /* form UPIU before issuing the command */
1361 ufshcd_compose_upiu(hba, lrbp);
1362 err = ufshcd_map_sg(lrbp);
1365 clear_bit_unlock(tag, &hba->lrb_in_use);
1369 /* issue command to the controller */
1370 spin_lock_irqsave(hba->host->host_lock, flags);
1371 ufshcd_send_command(hba, tag);
1373 spin_unlock_irqrestore(hba->host->host_lock, flags);
1378 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1379 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1382 lrbp->sense_bufflen = 0;
1383 lrbp->sense_buffer = NULL;
1384 lrbp->task_tag = tag;
1385 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1386 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1387 lrbp->intr_cmd = true; /* No interrupt aggregation */
1388 hba->dev_cmd.type = cmd_type;
1390 return ufshcd_compose_upiu(hba, lrbp);
1394 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1397 unsigned long flags;
1398 u32 mask = 1 << tag;
1400 /* clear outstanding transaction before retry */
1401 spin_lock_irqsave(hba->host->host_lock, flags);
1402 ufshcd_utrl_clear(hba, tag);
1403 spin_unlock_irqrestore(hba->host->host_lock, flags);
1406 * wait for for h/w to clear corresponding bit in door-bell.
1407 * max. wait is 1 sec.
1409 err = ufshcd_wait_for_register(hba,
1410 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1411 mask, ~mask, 1000, 1000);
1417 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1419 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1421 /* Get the UPIU response */
1422 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1423 UPIU_RSP_CODE_OFFSET;
1424 return query_res->response;
1428 * ufshcd_dev_cmd_completion() - handles device management command responses
1429 * @hba: per adapter instance
1430 * @lrbp: pointer to local reference block
1433 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1438 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1441 case UPIU_TRANSACTION_NOP_IN:
1442 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1444 dev_err(hba->dev, "%s: unexpected response %x\n",
1448 case UPIU_TRANSACTION_QUERY_RSP:
1449 err = ufshcd_check_query_response(hba, lrbp);
1451 err = ufshcd_copy_query_response(hba, lrbp);
1453 case UPIU_TRANSACTION_REJECT_UPIU:
1454 /* TODO: handle Reject UPIU Response */
1456 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1461 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1469 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1470 struct ufshcd_lrb *lrbp, int max_timeout)
1473 unsigned long time_left;
1474 unsigned long flags;
1476 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1477 msecs_to_jiffies(max_timeout));
1479 spin_lock_irqsave(hba->host->host_lock, flags);
1480 hba->dev_cmd.complete = NULL;
1481 if (likely(time_left)) {
1482 err = ufshcd_get_tr_ocs(lrbp);
1484 err = ufshcd_dev_cmd_completion(hba, lrbp);
1486 spin_unlock_irqrestore(hba->host->host_lock, flags);
1490 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1491 /* sucessfully cleared the command, retry if needed */
1499 * ufshcd_get_dev_cmd_tag - Get device management command tag
1500 * @hba: per-adapter instance
1501 * @tag: pointer to variable with available slot value
1503 * Get a free slot and lock it until device management command
1506 * Returns false if free slot is unavailable for locking, else
1507 * return true with tag value in @tag.
1509 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1519 tmp = ~hba->lrb_in_use;
1520 tag = find_last_bit(&tmp, hba->nutrs);
1521 if (tag >= hba->nutrs)
1523 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1531 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1533 clear_bit_unlock(tag, &hba->lrb_in_use);
1537 * ufshcd_exec_dev_cmd - API for sending device management requests
1539 * @cmd_type - specifies the type (NOP, Query...)
1540 * @timeout - time in seconds
1542 * NOTE: Since there is only one available tag for device management commands,
1543 * it is expected you hold the hba->dev_cmd.lock mutex.
1545 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1546 enum dev_cmd_type cmd_type, int timeout)
1548 struct ufshcd_lrb *lrbp;
1551 struct completion wait;
1552 unsigned long flags;
1555 * Get free slot, sleep if slots are unavailable.
1556 * Even though we use wait_event() which sleeps indefinitely,
1557 * the maximum wait time is bounded by SCSI request timeout.
1559 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1561 init_completion(&wait);
1562 lrbp = &hba->lrb[tag];
1564 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1568 hba->dev_cmd.complete = &wait;
1570 spin_lock_irqsave(hba->host->host_lock, flags);
1571 ufshcd_send_command(hba, tag);
1572 spin_unlock_irqrestore(hba->host->host_lock, flags);
1574 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1577 ufshcd_put_dev_cmd_tag(hba, tag);
1578 wake_up(&hba->dev_cmd.tag_wq);
1583 * ufshcd_init_query() - init the query response and request parameters
1584 * @hba: per-adapter instance
1585 * @request: address of the request pointer to be initialized
1586 * @response: address of the response pointer to be initialized
1587 * @opcode: operation to perform
1588 * @idn: flag idn to access
1589 * @index: LU number to access
1590 * @selector: query/flag/descriptor further identification
1592 static inline void ufshcd_init_query(struct ufs_hba *hba,
1593 struct ufs_query_req **request, struct ufs_query_res **response,
1594 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1596 *request = &hba->dev_cmd.query.request;
1597 *response = &hba->dev_cmd.query.response;
1598 memset(*request, 0, sizeof(struct ufs_query_req));
1599 memset(*response, 0, sizeof(struct ufs_query_res));
1600 (*request)->upiu_req.opcode = opcode;
1601 (*request)->upiu_req.idn = idn;
1602 (*request)->upiu_req.index = index;
1603 (*request)->upiu_req.selector = selector;
1607 * ufshcd_query_flag() - API function for sending flag query requests
1608 * hba: per-adapter instance
1609 * query_opcode: flag query to perform
1610 * idn: flag idn to access
1611 * flag_res: the flag value after the query request completes
1613 * Returns 0 for success, non-zero in case of failure
1615 static int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1616 enum flag_idn idn, bool *flag_res)
1618 struct ufs_query_req *request = NULL;
1619 struct ufs_query_res *response = NULL;
1620 int err, index = 0, selector = 0;
1624 ufshcd_hold(hba, false);
1625 mutex_lock(&hba->dev_cmd.lock);
1626 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1630 case UPIU_QUERY_OPCODE_SET_FLAG:
1631 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1632 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1633 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1635 case UPIU_QUERY_OPCODE_READ_FLAG:
1636 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1638 /* No dummy reads */
1639 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1647 "%s: Expected query flag opcode but got = %d\n",
1653 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1657 "%s: Sending flag query for idn %d failed, err = %d\n",
1658 __func__, idn, err);
1663 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1664 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1667 mutex_unlock(&hba->dev_cmd.lock);
1668 ufshcd_release(hba);
1673 * ufshcd_query_attr - API function for sending attribute requests
1674 * hba: per-adapter instance
1675 * opcode: attribute opcode
1676 * idn: attribute idn to access
1677 * index: index field
1678 * selector: selector field
1679 * attr_val: the attribute value after the query request completes
1681 * Returns 0 for success, non-zero in case of failure
1683 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1684 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1686 struct ufs_query_req *request = NULL;
1687 struct ufs_query_res *response = NULL;
1692 ufshcd_hold(hba, false);
1694 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1700 mutex_lock(&hba->dev_cmd.lock);
1701 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1705 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1706 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1707 request->upiu_req.value = cpu_to_be32(*attr_val);
1709 case UPIU_QUERY_OPCODE_READ_ATTR:
1710 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1713 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1719 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1722 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1723 __func__, opcode, idn, err);
1727 *attr_val = be32_to_cpu(response->upiu_res.value);
1730 mutex_unlock(&hba->dev_cmd.lock);
1732 ufshcd_release(hba);
1737 * ufshcd_query_descriptor - API function for sending descriptor requests
1738 * hba: per-adapter instance
1739 * opcode: attribute opcode
1740 * idn: attribute idn to access
1741 * index: index field
1742 * selector: selector field
1743 * desc_buf: the buffer that contains the descriptor
1744 * buf_len: length parameter passed to the device
1746 * Returns 0 for success, non-zero in case of failure.
1747 * The buf_len parameter will contain, on return, the length parameter
1748 * received on the response.
1750 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1751 enum query_opcode opcode, enum desc_idn idn, u8 index,
1752 u8 selector, u8 *desc_buf, int *buf_len)
1754 struct ufs_query_req *request = NULL;
1755 struct ufs_query_res *response = NULL;
1760 ufshcd_hold(hba, false);
1762 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1768 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1769 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1770 __func__, *buf_len);
1775 mutex_lock(&hba->dev_cmd.lock);
1776 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1778 hba->dev_cmd.query.descriptor = desc_buf;
1779 request->upiu_req.length = cpu_to_be16(*buf_len);
1782 case UPIU_QUERY_OPCODE_WRITE_DESC:
1783 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1785 case UPIU_QUERY_OPCODE_READ_DESC:
1786 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1790 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1796 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1799 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1800 __func__, opcode, idn, err);
1804 hba->dev_cmd.query.descriptor = NULL;
1805 *buf_len = be16_to_cpu(response->upiu_res.length);
1808 mutex_unlock(&hba->dev_cmd.lock);
1810 ufshcd_release(hba);
1815 * ufshcd_read_desc_param - read the specified descriptor parameter
1816 * @hba: Pointer to adapter instance
1817 * @desc_id: descriptor idn value
1818 * @desc_index: descriptor index
1819 * @param_offset: offset of the parameter to read
1820 * @param_read_buf: pointer to buffer where parameter would be read
1821 * @param_size: sizeof(param_read_buf)
1823 * Return 0 in case of success, non-zero otherwise
1825 static int ufshcd_read_desc_param(struct ufs_hba *hba,
1826 enum desc_idn desc_id,
1835 bool is_kmalloc = true;
1838 if (desc_id >= QUERY_DESC_IDN_MAX)
1841 buff_len = ufs_query_desc_max_size[desc_id];
1842 if ((param_offset + param_size) > buff_len)
1845 if (!param_offset && (param_size == buff_len)) {
1846 /* memory space already available to hold full descriptor */
1847 desc_buf = param_read_buf;
1850 /* allocate memory to hold full descriptor */
1851 desc_buf = kmalloc(buff_len, GFP_KERNEL);
1856 ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
1857 desc_id, desc_index, 0, desc_buf,
1860 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
1861 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
1862 ufs_query_desc_max_size[desc_id])
1863 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
1864 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
1865 __func__, desc_id, param_offset, buff_len, ret);
1873 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
1880 static inline int ufshcd_read_desc(struct ufs_hba *hba,
1881 enum desc_idn desc_id,
1886 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
1889 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
1893 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
1897 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
1898 * @hba: Pointer to adapter instance
1900 * @param_offset: offset of the parameter to read
1901 * @param_read_buf: pointer to buffer where parameter would be read
1902 * @param_size: sizeof(param_read_buf)
1904 * Return 0 in case of success, non-zero otherwise
1906 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
1908 enum unit_desc_param param_offset,
1913 * Unit descriptors are only available for general purpose LUs (LUN id
1914 * from 0 to 7) and RPMB Well known LU.
1916 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
1919 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
1920 param_offset, param_read_buf, param_size);
1924 * ufshcd_memory_alloc - allocate memory for host memory space data structures
1925 * @hba: per adapter instance
1927 * 1. Allocate DMA memory for Command Descriptor array
1928 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
1929 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
1930 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
1932 * 4. Allocate memory for local reference block(lrb).
1934 * Returns 0 for success, non-zero in case of failure
1936 static int ufshcd_memory_alloc(struct ufs_hba *hba)
1938 size_t utmrdl_size, utrdl_size, ucdl_size;
1940 /* Allocate memory for UTP command descriptors */
1941 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
1942 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
1944 &hba->ucdl_dma_addr,
1948 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
1949 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
1950 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
1951 * be aligned to 128 bytes as well
1953 if (!hba->ucdl_base_addr ||
1954 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
1956 "Command Descriptor Memory allocation failed\n");
1961 * Allocate memory for UTP Transfer descriptors
1962 * UFSHCI requires 1024 byte alignment of UTRD
1964 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
1965 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
1967 &hba->utrdl_dma_addr,
1969 if (!hba->utrdl_base_addr ||
1970 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
1972 "Transfer Descriptor Memory allocation failed\n");
1977 * Allocate memory for UTP Task Management descriptors
1978 * UFSHCI requires 1024 byte alignment of UTMRD
1980 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
1981 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
1983 &hba->utmrdl_dma_addr,
1985 if (!hba->utmrdl_base_addr ||
1986 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
1988 "Task Management Descriptor Memory allocation failed\n");
1992 /* Allocate memory for local reference block */
1993 hba->lrb = devm_kzalloc(hba->dev,
1994 hba->nutrs * sizeof(struct ufshcd_lrb),
1997 dev_err(hba->dev, "LRB Memory allocation failed\n");
2006 * ufshcd_host_memory_configure - configure local reference block with
2008 * @hba: per adapter instance
2010 * Configure Host memory space
2011 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2013 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2015 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2016 * into local reference block.
2018 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2020 struct utp_transfer_cmd_desc *cmd_descp;
2021 struct utp_transfer_req_desc *utrdlp;
2022 dma_addr_t cmd_desc_dma_addr;
2023 dma_addr_t cmd_desc_element_addr;
2024 u16 response_offset;
2029 utrdlp = hba->utrdl_base_addr;
2030 cmd_descp = hba->ucdl_base_addr;
2033 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2035 offsetof(struct utp_transfer_cmd_desc, prd_table);
2037 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2038 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2040 for (i = 0; i < hba->nutrs; i++) {
2041 /* Configure UTRD with command descriptor base address */
2042 cmd_desc_element_addr =
2043 (cmd_desc_dma_addr + (cmd_desc_size * i));
2044 utrdlp[i].command_desc_base_addr_lo =
2045 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2046 utrdlp[i].command_desc_base_addr_hi =
2047 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2049 /* Response upiu and prdt offset should be in double words */
2050 utrdlp[i].response_upiu_offset =
2051 cpu_to_le16((response_offset >> 2));
2052 utrdlp[i].prd_table_offset =
2053 cpu_to_le16((prdt_offset >> 2));
2054 utrdlp[i].response_upiu_length =
2055 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2057 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2058 hba->lrb[i].ucd_req_ptr =
2059 (struct utp_upiu_req *)(cmd_descp + i);
2060 hba->lrb[i].ucd_rsp_ptr =
2061 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2062 hba->lrb[i].ucd_prdt_ptr =
2063 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2068 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2069 * @hba: per adapter instance
2071 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2072 * in order to initialize the Unipro link startup procedure.
2073 * Once the Unipro links are up, the device connected to the controller
2076 * Returns 0 on success, non-zero value on failure
2078 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2080 struct uic_command uic_cmd = {0};
2083 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2085 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2088 "dme-link-startup: error code %d\n", ret);
2092 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2094 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2095 unsigned long min_sleep_time_us;
2097 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2101 * last_dme_cmd_tstamp will be 0 only for 1st call to
2104 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2105 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2107 unsigned long delta =
2108 (unsigned long) ktime_to_us(
2109 ktime_sub(ktime_get(),
2110 hba->last_dme_cmd_tstamp));
2112 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2114 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2116 return; /* no more delay required */
2119 /* allow sleep for extra 50us if needed */
2120 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2124 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2125 * @hba: per adapter instance
2126 * @attr_sel: uic command argument1
2127 * @attr_set: attribute set type as uic command argument2
2128 * @mib_val: setting value as uic command argument3
2129 * @peer: indicate whether peer or local
2131 * Returns 0 on success, non-zero value on failure
2133 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2134 u8 attr_set, u32 mib_val, u8 peer)
2136 struct uic_command uic_cmd = {0};
2137 static const char *const action[] = {
2141 const char *set = action[!!peer];
2144 uic_cmd.command = peer ?
2145 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2146 uic_cmd.argument1 = attr_sel;
2147 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2148 uic_cmd.argument3 = mib_val;
2150 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2152 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2153 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2157 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2160 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2161 * @hba: per adapter instance
2162 * @attr_sel: uic command argument1
2163 * @mib_val: the value of the attribute as returned by the UIC command
2164 * @peer: indicate whether peer or local
2166 * Returns 0 on success, non-zero value on failure
2168 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2169 u32 *mib_val, u8 peer)
2171 struct uic_command uic_cmd = {0};
2172 static const char *const action[] = {
2176 const char *get = action[!!peer];
2178 struct ufs_pa_layer_attr orig_pwr_info;
2179 struct ufs_pa_layer_attr temp_pwr_info;
2180 bool pwr_mode_change = false;
2182 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2183 orig_pwr_info = hba->pwr_info;
2184 temp_pwr_info = orig_pwr_info;
2186 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2187 orig_pwr_info.pwr_rx == FAST_MODE) {
2188 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2189 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2190 pwr_mode_change = true;
2191 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2192 orig_pwr_info.pwr_rx == SLOW_MODE) {
2193 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2194 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2195 pwr_mode_change = true;
2197 if (pwr_mode_change) {
2198 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2204 uic_cmd.command = peer ?
2205 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2206 uic_cmd.argument1 = attr_sel;
2208 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2210 dev_err(hba->dev, "%s: attr-id 0x%x error code %d\n",
2211 get, UIC_GET_ATTR_ID(attr_sel), ret);
2216 *mib_val = uic_cmd.argument3;
2218 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2220 ufshcd_change_power_mode(hba, &orig_pwr_info);
2224 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2227 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2228 * state) and waits for it to take effect.
2230 * @hba: per adapter instance
2231 * @cmd: UIC command to execute
2233 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2234 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2235 * and device UniPro link and hence it's final completion would be indicated by
2236 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2237 * addition to normal UIC command completion Status (UCCS). This function only
2238 * returns after the relevant status bits indicate the completion.
2240 * Returns 0 on success, non-zero value on failure
2242 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2244 struct completion uic_async_done;
2245 unsigned long flags;
2249 mutex_lock(&hba->uic_cmd_mutex);
2250 init_completion(&uic_async_done);
2251 ufshcd_add_delay_before_dme_cmd(hba);
2253 spin_lock_irqsave(hba->host->host_lock, flags);
2254 hba->uic_async_done = &uic_async_done;
2255 ret = __ufshcd_send_uic_cmd(hba, cmd);
2256 spin_unlock_irqrestore(hba->host->host_lock, flags);
2259 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2260 cmd->command, cmd->argument3, ret);
2263 ret = ufshcd_wait_for_uic_cmd(hba, cmd);
2266 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2267 cmd->command, cmd->argument3, ret);
2271 if (!wait_for_completion_timeout(hba->uic_async_done,
2272 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2274 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2275 cmd->command, cmd->argument3);
2280 status = ufshcd_get_upmcrs(hba);
2281 if (status != PWR_LOCAL) {
2283 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2284 cmd->command, status);
2285 ret = (status != PWR_OK) ? status : -1;
2288 spin_lock_irqsave(hba->host->host_lock, flags);
2289 hba->uic_async_done = NULL;
2290 spin_unlock_irqrestore(hba->host->host_lock, flags);
2291 mutex_unlock(&hba->uic_cmd_mutex);
2297 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2298 * using DME_SET primitives.
2299 * @hba: per adapter instance
2300 * @mode: powr mode value
2302 * Returns 0 on success, non-zero value on failure
2304 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2306 struct uic_command uic_cmd = {0};
2309 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2310 ret = ufshcd_dme_set(hba,
2311 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2313 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2319 uic_cmd.command = UIC_CMD_DME_SET;
2320 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2321 uic_cmd.argument3 = mode;
2322 ufshcd_hold(hba, false);
2323 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2324 ufshcd_release(hba);
2330 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2332 struct uic_command uic_cmd = {0};
2334 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2336 return ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2339 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2341 struct uic_command uic_cmd = {0};
2344 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2345 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2347 ufshcd_set_link_off(hba);
2348 ret = ufshcd_host_reset_and_restore(hba);
2355 * ufshcd_init_pwr_info - setting the POR (power on reset)
2356 * values in hba power info
2357 * @hba: per-adapter instance
2359 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2361 hba->pwr_info.gear_rx = UFS_PWM_G1;
2362 hba->pwr_info.gear_tx = UFS_PWM_G1;
2363 hba->pwr_info.lane_rx = 1;
2364 hba->pwr_info.lane_tx = 1;
2365 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2366 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2367 hba->pwr_info.hs_rate = 0;
2371 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2372 * @hba: per-adapter instance
2374 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2376 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2378 if (hba->max_pwr_info.is_valid)
2381 pwr_info->pwr_tx = FASTAUTO_MODE;
2382 pwr_info->pwr_rx = FASTAUTO_MODE;
2383 pwr_info->hs_rate = PA_HS_MODE_B;
2385 /* Get the connected lane count */
2386 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2387 &pwr_info->lane_rx);
2388 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2389 &pwr_info->lane_tx);
2391 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2392 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2400 * First, get the maximum gears of HS speed.
2401 * If a zero value, it means there is no HSGEAR capability.
2402 * Then, get the maximum gears of PWM speed.
2404 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2405 if (!pwr_info->gear_rx) {
2406 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2407 &pwr_info->gear_rx);
2408 if (!pwr_info->gear_rx) {
2409 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2410 __func__, pwr_info->gear_rx);
2413 pwr_info->pwr_rx = SLOWAUTO_MODE;
2416 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2417 &pwr_info->gear_tx);
2418 if (!pwr_info->gear_tx) {
2419 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2420 &pwr_info->gear_tx);
2421 if (!pwr_info->gear_tx) {
2422 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2423 __func__, pwr_info->gear_tx);
2426 pwr_info->pwr_tx = SLOWAUTO_MODE;
2429 hba->max_pwr_info.is_valid = true;
2433 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2434 struct ufs_pa_layer_attr *pwr_mode)
2438 /* if already configured to the requested pwr_mode */
2439 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2440 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2441 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2442 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2443 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2444 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2445 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2446 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2451 * Configure attributes for power mode change with below.
2452 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2453 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2456 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2457 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2459 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2460 pwr_mode->pwr_rx == FAST_MODE)
2461 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2463 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2465 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2466 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2468 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2469 pwr_mode->pwr_tx == FAST_MODE)
2470 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2472 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2474 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2475 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2476 pwr_mode->pwr_rx == FAST_MODE ||
2477 pwr_mode->pwr_tx == FAST_MODE)
2478 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2481 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2482 | pwr_mode->pwr_tx);
2486 "%s: power mode change failed %d\n", __func__, ret);
2488 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2491 memcpy(&hba->pwr_info, pwr_mode,
2492 sizeof(struct ufs_pa_layer_attr));
2499 * ufshcd_config_pwr_mode - configure a new power mode
2500 * @hba: per-adapter instance
2501 * @desired_pwr_mode: desired power configuration
2503 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2504 struct ufs_pa_layer_attr *desired_pwr_mode)
2506 struct ufs_pa_layer_attr final_params = { 0 };
2509 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2510 desired_pwr_mode, &final_params);
2513 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2515 ret = ufshcd_change_power_mode(hba, &final_params);
2521 * ufshcd_complete_dev_init() - checks device readiness
2522 * hba: per-adapter instance
2524 * Set fDeviceInit flag and poll until device toggles it.
2526 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2528 int i, retries, err = 0;
2531 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2532 /* Set the fDeviceInit flag */
2533 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2534 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2535 if (!err || err == -ETIMEDOUT)
2537 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
2541 "%s setting fDeviceInit flag failed with error %d\n",
2546 /* poll for max. 100 iterations for fDeviceInit flag to clear */
2547 for (i = 0; i < 100 && !err && flag_res; i++) {
2548 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2549 err = ufshcd_query_flag(hba,
2550 UPIU_QUERY_OPCODE_READ_FLAG,
2551 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2552 if (!err || err == -ETIMEDOUT)
2554 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__,
2560 "%s reading fDeviceInit flag failed with error %d\n",
2564 "%s fDeviceInit was not cleared by the device\n",
2572 * ufshcd_make_hba_operational - Make UFS controller operational
2573 * @hba: per adapter instance
2575 * To bring UFS host controller to operational state,
2576 * 1. Enable required interrupts
2577 * 2. Configure interrupt aggregation
2578 * 3. Program UTRL and UTMRL base addres
2579 * 4. Configure run-stop-registers
2581 * Returns 0 on success, non-zero value on failure
2583 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2588 /* Enable required interrupts */
2589 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2591 /* Configure interrupt aggregation */
2592 if (ufshcd_is_intr_aggr_allowed(hba))
2593 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2595 ufshcd_disable_intr_aggr(hba);
2597 /* Configure UTRL and UTMRL base address registers */
2598 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2599 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2600 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2601 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2602 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2603 REG_UTP_TASK_REQ_LIST_BASE_L);
2604 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2605 REG_UTP_TASK_REQ_LIST_BASE_H);
2608 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2609 * DEI, HEI bits must be 0
2611 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2612 if (!(ufshcd_get_lists_status(reg))) {
2613 ufshcd_enable_run_stop_reg(hba);
2616 "Host controller not ready to process requests");
2626 * ufshcd_hba_enable - initialize the controller
2627 * @hba: per adapter instance
2629 * The controller resets itself and controller firmware initialization
2630 * sequence kicks off. When controller is ready it will set
2631 * the Host Controller Enable bit to 1.
2633 * Returns 0 on success, non-zero value on failure
2635 static int ufshcd_hba_enable(struct ufs_hba *hba)
2640 * msleep of 1 and 5 used in this function might result in msleep(20),
2641 * but it was necessary to send the UFS FPGA to reset mode during
2642 * development and testing of this driver. msleep can be changed to
2643 * mdelay and retry count can be reduced based on the controller.
2645 if (!ufshcd_is_hba_active(hba)) {
2647 /* change controller state to "reset state" */
2648 ufshcd_hba_stop(hba);
2651 * This delay is based on the testing done with UFS host
2652 * controller FPGA. The delay can be changed based on the
2653 * host controller used.
2658 /* UniPro link is disabled at this point */
2659 ufshcd_set_link_off(hba);
2661 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
2663 /* start controller initialization sequence */
2664 ufshcd_hba_start(hba);
2667 * To initialize a UFS host controller HCE bit must be set to 1.
2668 * During initialization the HCE bit value changes from 1->0->1.
2669 * When the host controller completes initialization sequence
2670 * it sets the value of HCE bit to 1. The same HCE bit is read back
2671 * to check if the controller has completed initialization sequence.
2672 * So without this delay the value HCE = 1, set in the previous
2673 * instruction might be read back.
2674 * This delay can be changed based on the controller.
2678 /* wait for the host controller to complete initialization */
2680 while (ufshcd_is_hba_active(hba)) {
2685 "Controller enable failed\n");
2691 /* enable UIC related interrupts */
2692 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
2694 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
2699 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
2701 int tx_lanes, i, err = 0;
2704 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2707 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2709 for (i = 0; i < tx_lanes; i++) {
2711 err = ufshcd_dme_set(hba,
2712 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2713 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2716 err = ufshcd_dme_peer_set(hba,
2717 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2718 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2721 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
2722 __func__, peer, i, err);
2730 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
2732 return ufshcd_disable_tx_lcc(hba, true);
2736 * ufshcd_link_startup - Initialize unipro link startup
2737 * @hba: per adapter instance
2739 * Returns 0 for success, non-zero in case of failure
2741 static int ufshcd_link_startup(struct ufs_hba *hba)
2744 int retries = DME_LINKSTARTUP_RETRIES;
2747 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
2749 ret = ufshcd_dme_link_startup(hba);
2751 /* check if device is detected by inter-connect layer */
2752 if (!ret && !ufshcd_is_device_present(hba)) {
2753 dev_err(hba->dev, "%s: Device not present\n", __func__);
2759 * DME link lost indication is only received when link is up,
2760 * but we can't be sure if the link is up until link startup
2761 * succeeds. So reset the local Uni-Pro and try again.
2763 if (ret && ufshcd_hba_enable(hba))
2765 } while (ret && retries--);
2768 /* failed to get the link up... retire */
2771 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
2772 ret = ufshcd_disable_device_tx_lcc(hba);
2777 /* Include any host controller configuration via UIC commands */
2778 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
2782 ret = ufshcd_make_hba_operational(hba);
2785 dev_err(hba->dev, "link startup failed %d\n", ret);
2790 * ufshcd_verify_dev_init() - Verify device initialization
2791 * @hba: per-adapter instance
2793 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
2794 * device Transport Protocol (UTP) layer is ready after a reset.
2795 * If the UTP layer at the device side is not initialized, it may
2796 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
2797 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
2799 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
2804 ufshcd_hold(hba, false);
2805 mutex_lock(&hba->dev_cmd.lock);
2806 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
2807 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
2810 if (!err || err == -ETIMEDOUT)
2813 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
2815 mutex_unlock(&hba->dev_cmd.lock);
2816 ufshcd_release(hba);
2819 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
2824 * ufshcd_set_queue_depth - set lun queue depth
2825 * @sdev: pointer to SCSI device
2827 * Read bLUQueueDepth value and activate scsi tagged command
2828 * queueing. For WLUN, queue depth is set to 1. For best-effort
2829 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
2830 * value that host can queue.
2832 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
2836 struct ufs_hba *hba;
2838 hba = shost_priv(sdev->host);
2840 lun_qdepth = hba->nutrs;
2841 ret = ufshcd_read_unit_desc_param(hba,
2842 ufshcd_scsi_to_upiu_lun(sdev->lun),
2843 UNIT_DESC_PARAM_LU_Q_DEPTH,
2845 sizeof(lun_qdepth));
2847 /* Some WLUN doesn't support unit descriptor */
2848 if (ret == -EOPNOTSUPP)
2850 else if (!lun_qdepth)
2851 /* eventually, we can figure out the real queue depth */
2852 lun_qdepth = hba->nutrs;
2854 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
2856 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
2857 __func__, lun_qdepth);
2858 scsi_change_queue_depth(sdev, lun_qdepth);
2862 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
2863 * @hba: per-adapter instance
2864 * @lun: UFS device lun id
2865 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
2867 * Returns 0 in case of success and b_lu_write_protect status would be returned
2868 * @b_lu_write_protect parameter.
2869 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
2870 * Returns -EINVAL in case of invalid parameters passed to this function.
2872 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
2874 u8 *b_lu_write_protect)
2878 if (!b_lu_write_protect)
2881 * According to UFS device spec, RPMB LU can't be write
2882 * protected so skip reading bLUWriteProtect parameter for
2883 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
2885 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
2888 ret = ufshcd_read_unit_desc_param(hba,
2890 UNIT_DESC_PARAM_LU_WR_PROTECT,
2892 sizeof(*b_lu_write_protect));
2897 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
2899 * @hba: per-adapter instance
2900 * @sdev: pointer to SCSI device
2903 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
2904 struct scsi_device *sdev)
2906 if (hba->dev_info.f_power_on_wp_en &&
2907 !hba->dev_info.is_lu_power_on_wp) {
2908 u8 b_lu_write_protect;
2910 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
2911 &b_lu_write_protect) &&
2912 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
2913 hba->dev_info.is_lu_power_on_wp = true;
2918 * ufshcd_slave_alloc - handle initial SCSI device configurations
2919 * @sdev: pointer to SCSI device
2923 static int ufshcd_slave_alloc(struct scsi_device *sdev)
2925 struct ufs_hba *hba;
2927 hba = shost_priv(sdev->host);
2929 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
2930 sdev->use_10_for_ms = 1;
2932 /* allow SCSI layer to restart the device in case of errors */
2933 sdev->allow_restart = 1;
2935 /* REPORT SUPPORTED OPERATION CODES is not supported */
2936 sdev->no_report_opcodes = 1;
2939 ufshcd_set_queue_depth(sdev);
2941 ufshcd_get_lu_power_on_wp_status(hba, sdev);
2947 * ufshcd_change_queue_depth - change queue depth
2948 * @sdev: pointer to SCSI device
2949 * @depth: required depth to set
2951 * Change queue depth and make sure the max. limits are not crossed.
2953 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
2955 struct ufs_hba *hba = shost_priv(sdev->host);
2957 if (depth > hba->nutrs)
2959 return scsi_change_queue_depth(sdev, depth);
2963 * ufshcd_slave_configure - adjust SCSI device configurations
2964 * @sdev: pointer to SCSI device
2966 static int ufshcd_slave_configure(struct scsi_device *sdev)
2968 struct request_queue *q = sdev->request_queue;
2970 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
2971 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
2977 * ufshcd_slave_destroy - remove SCSI device configurations
2978 * @sdev: pointer to SCSI device
2980 static void ufshcd_slave_destroy(struct scsi_device *sdev)
2982 struct ufs_hba *hba;
2984 hba = shost_priv(sdev->host);
2985 /* Drop the reference as it won't be needed anymore */
2986 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
2987 unsigned long flags;
2989 spin_lock_irqsave(hba->host->host_lock, flags);
2990 hba->sdev_ufs_device = NULL;
2991 spin_unlock_irqrestore(hba->host->host_lock, flags);
2996 * ufshcd_task_req_compl - handle task management request completion
2997 * @hba: per adapter instance
2998 * @index: index of the completed request
2999 * @resp: task management service response
3001 * Returns non-zero value on error, zero on success
3003 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3005 struct utp_task_req_desc *task_req_descp;
3006 struct utp_upiu_task_rsp *task_rsp_upiup;
3007 unsigned long flags;
3011 spin_lock_irqsave(hba->host->host_lock, flags);
3013 /* Clear completed tasks from outstanding_tasks */
3014 __clear_bit(index, &hba->outstanding_tasks);
3016 task_req_descp = hba->utmrdl_base_addr;
3017 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3019 if (ocs_value == OCS_SUCCESS) {
3020 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3021 task_req_descp[index].task_rsp_upiu;
3022 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
3023 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
3025 *resp = (u8)task_result;
3027 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3028 __func__, ocs_value);
3030 spin_unlock_irqrestore(hba->host->host_lock, flags);
3036 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3037 * @lrb: pointer to local reference block of completed command
3038 * @scsi_status: SCSI command status
3040 * Returns value base on SCSI command status
3043 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3047 switch (scsi_status) {
3048 case SAM_STAT_CHECK_CONDITION:
3049 ufshcd_copy_sense_data(lrbp);
3051 result |= DID_OK << 16 |
3052 COMMAND_COMPLETE << 8 |
3055 case SAM_STAT_TASK_SET_FULL:
3057 case SAM_STAT_TASK_ABORTED:
3058 ufshcd_copy_sense_data(lrbp);
3059 result |= scsi_status;
3062 result |= DID_ERROR << 16;
3064 } /* end of switch */
3070 * ufshcd_transfer_rsp_status - Get overall status of the response
3071 * @hba: per adapter instance
3072 * @lrb: pointer to local reference block of completed command
3074 * Returns result of the command to notify SCSI midlayer
3077 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3083 /* overall command status of utrd */
3084 ocs = ufshcd_get_tr_ocs(lrbp);
3088 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3091 case UPIU_TRANSACTION_RESPONSE:
3093 * get the response UPIU result to extract
3094 * the SCSI command status
3096 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3099 * get the result based on SCSI status response
3100 * to notify the SCSI midlayer of the command status
3102 scsi_status = result & MASK_SCSI_STATUS;
3103 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3105 if (ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3106 schedule_work(&hba->eeh_work);
3108 case UPIU_TRANSACTION_REJECT_UPIU:
3109 /* TODO: handle Reject UPIU Response */
3110 result = DID_ERROR << 16;
3112 "Reject UPIU not fully implemented\n");
3115 result = DID_ERROR << 16;
3117 "Unexpected request response code = %x\n",
3123 result |= DID_ABORT << 16;
3125 case OCS_INVALID_COMMAND_STATUS:
3126 result |= DID_REQUEUE << 16;
3128 case OCS_INVALID_CMD_TABLE_ATTR:
3129 case OCS_INVALID_PRDT_ATTR:
3130 case OCS_MISMATCH_DATA_BUF_SIZE:
3131 case OCS_MISMATCH_RESP_UPIU_SIZE:
3132 case OCS_PEER_COMM_FAILURE:
3133 case OCS_FATAL_ERROR:
3135 result |= DID_ERROR << 16;
3137 "OCS error from controller = %x\n", ocs);
3139 } /* end of switch */
3145 * ufshcd_uic_cmd_compl - handle completion of uic command
3146 * @hba: per adapter instance
3147 * @intr_status: interrupt status generated by the controller
3149 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3151 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3152 hba->active_uic_cmd->argument2 |=
3153 ufshcd_get_uic_cmd_result(hba);
3154 hba->active_uic_cmd->argument3 =
3155 ufshcd_get_dme_attr_val(hba);
3156 complete(&hba->active_uic_cmd->done);
3159 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3160 complete(hba->uic_async_done);
3164 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3165 * @hba: per adapter instance
3167 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3169 struct ufshcd_lrb *lrbp;
3170 struct scsi_cmnd *cmd;
3171 unsigned long completed_reqs;
3175 struct request *req;
3177 /* Resetting interrupt aggregation counters first and reading the
3178 * DOOR_BELL afterward allows us to handle all the completed requests.
3179 * In order to prevent other interrupts starvation the DB is read once
3180 * after reset. The down side of this solution is the possibility of
3181 * false interrupt if device completes another request after resetting
3182 * aggregation and before reading the DB.
3184 if (ufshcd_is_intr_aggr_allowed(hba))
3185 ufshcd_reset_intr_aggr(hba);
3187 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3188 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3190 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3191 lrbp = &hba->lrb[index];
3194 result = ufshcd_transfer_rsp_status(hba, lrbp);
3195 scsi_dma_unmap(cmd);
3196 cmd->result = result;
3197 /* Mark completed command as NULL in LRB */
3199 clear_bit_unlock(index, &hba->lrb_in_use);
3202 /* Update IO svc time latency histogram */
3203 if (req->lat_hist_enabled) {
3207 completion = ktime_get();
3208 delta_us = ktime_us_delta(completion,
3209 req->lat_hist_io_start);
3210 /* rq_data_dir() => true if WRITE */
3211 blk_update_latency_hist(&hba->io_lat_s,
3212 (rq_data_dir(req) == READ),
3216 /* Do not touch lrbp after scsi done */
3217 cmd->scsi_done(cmd);
3218 __ufshcd_release(hba);
3219 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3220 if (hba->dev_cmd.complete)
3221 complete(hba->dev_cmd.complete);
3225 /* clear corresponding bits of completed commands */
3226 hba->outstanding_reqs ^= completed_reqs;
3228 ufshcd_clk_scaling_update_busy(hba);
3230 /* we might have free'd some tags above */
3231 wake_up(&hba->dev_cmd.tag_wq);
3235 * ufshcd_disable_ee - disable exception event
3236 * @hba: per-adapter instance
3237 * @mask: exception event to disable
3239 * Disables exception event in the device so that the EVENT_ALERT
3242 * Returns zero on success, non-zero error value on failure.
3244 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3249 if (!(hba->ee_ctrl_mask & mask))
3252 val = hba->ee_ctrl_mask & ~mask;
3253 val &= 0xFFFF; /* 2 bytes */
3254 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3255 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3257 hba->ee_ctrl_mask &= ~mask;
3263 * ufshcd_enable_ee - enable exception event
3264 * @hba: per-adapter instance
3265 * @mask: exception event to enable
3267 * Enable corresponding exception event in the device to allow
3268 * device to alert host in critical scenarios.
3270 * Returns zero on success, non-zero error value on failure.
3272 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3277 if (hba->ee_ctrl_mask & mask)
3280 val = hba->ee_ctrl_mask | mask;
3281 val &= 0xFFFF; /* 2 bytes */
3282 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3283 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3285 hba->ee_ctrl_mask |= mask;
3291 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3292 * @hba: per-adapter instance
3294 * Allow device to manage background operations on its own. Enabling
3295 * this might lead to inconsistent latencies during normal data transfers
3296 * as the device is allowed to manage its own way of handling background
3299 * Returns zero on success, non-zero on failure.
3301 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3305 if (hba->auto_bkops_enabled)
3308 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3309 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3311 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3316 hba->auto_bkops_enabled = true;
3318 /* No need of URGENT_BKOPS exception from the device */
3319 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3321 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3328 * ufshcd_disable_auto_bkops - block device in doing background operations
3329 * @hba: per-adapter instance
3331 * Disabling background operations improves command response latency but
3332 * has drawback of device moving into critical state where the device is
3333 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3334 * host is idle so that BKOPS are managed effectively without any negative
3337 * Returns zero on success, non-zero on failure.
3339 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3343 if (!hba->auto_bkops_enabled)
3347 * If host assisted BKOPs is to be enabled, make sure
3348 * urgent bkops exception is allowed.
3350 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3352 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3357 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3358 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3360 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3362 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3366 hba->auto_bkops_enabled = false;
3372 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3373 * @hba: per adapter instance
3375 * After a device reset the device may toggle the BKOPS_EN flag
3376 * to default value. The s/w tracking variables should be updated
3377 * as well. Do this by forcing enable of auto bkops.
3379 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3381 hba->auto_bkops_enabled = false;
3382 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3383 ufshcd_enable_auto_bkops(hba);
3386 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3388 return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3389 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3393 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3394 * @hba: per-adapter instance
3395 * @status: bkops_status value
3397 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3398 * flag in the device to permit background operations if the device
3399 * bkops_status is greater than or equal to "status" argument passed to
3400 * this function, disable otherwise.
3402 * Returns 0 for success, non-zero in case of failure.
3404 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3405 * to know whether auto bkops is enabled or disabled after this function
3406 * returns control to it.
3408 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3409 enum bkops_status status)
3412 u32 curr_status = 0;
3414 err = ufshcd_get_bkops_status(hba, &curr_status);
3416 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3419 } else if (curr_status > BKOPS_STATUS_MAX) {
3420 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3421 __func__, curr_status);
3426 if (curr_status >= status)
3427 err = ufshcd_enable_auto_bkops(hba);
3429 err = ufshcd_disable_auto_bkops(hba);
3435 * ufshcd_urgent_bkops - handle urgent bkops exception event
3436 * @hba: per-adapter instance
3438 * Enable fBackgroundOpsEn flag in the device to permit background
3441 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3442 * and negative error value for any other failure.
3444 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3446 return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3449 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3451 return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3452 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3456 * ufshcd_exception_event_handler - handle exceptions raised by device
3457 * @work: pointer to work data
3459 * Read bExceptionEventStatus attribute from the device and handle the
3460 * exception event accordingly.
3462 static void ufshcd_exception_event_handler(struct work_struct *work)
3464 struct ufs_hba *hba;
3467 hba = container_of(work, struct ufs_hba, eeh_work);
3469 pm_runtime_get_sync(hba->dev);
3470 err = ufshcd_get_ee_status(hba, &status);
3472 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3477 status &= hba->ee_ctrl_mask;
3478 if (status & MASK_EE_URGENT_BKOPS) {
3479 err = ufshcd_urgent_bkops(hba);
3481 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3485 pm_runtime_put_sync(hba->dev);
3490 * ufshcd_err_handler - handle UFS errors that require s/w attention
3491 * @work: pointer to work structure
3493 static void ufshcd_err_handler(struct work_struct *work)
3495 struct ufs_hba *hba;
3496 unsigned long flags;
3502 hba = container_of(work, struct ufs_hba, eh_work);
3504 pm_runtime_get_sync(hba->dev);
3505 ufshcd_hold(hba, false);
3507 spin_lock_irqsave(hba->host->host_lock, flags);
3508 if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
3509 spin_unlock_irqrestore(hba->host->host_lock, flags);
3513 hba->ufshcd_state = UFSHCD_STATE_RESET;
3514 ufshcd_set_eh_in_progress(hba);
3516 /* Complete requests that have door-bell cleared by h/w */
3517 ufshcd_transfer_req_compl(hba);
3518 ufshcd_tmc_handler(hba);
3519 spin_unlock_irqrestore(hba->host->host_lock, flags);
3521 /* Clear pending transfer requests */
3522 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs)
3523 if (ufshcd_clear_cmd(hba, tag))
3524 err_xfer |= 1 << tag;
3526 /* Clear pending task management requests */
3527 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs)
3528 if (ufshcd_clear_tm_cmd(hba, tag))
3531 /* Complete the requests that are cleared by s/w */
3532 spin_lock_irqsave(hba->host->host_lock, flags);
3533 ufshcd_transfer_req_compl(hba);
3534 ufshcd_tmc_handler(hba);
3535 spin_unlock_irqrestore(hba->host->host_lock, flags);
3537 /* Fatal errors need reset */
3538 if (err_xfer || err_tm || (hba->saved_err & INT_FATAL_ERRORS) ||
3539 ((hba->saved_err & UIC_ERROR) &&
3540 (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR))) {
3541 err = ufshcd_reset_and_restore(hba);
3543 dev_err(hba->dev, "%s: reset and restore failed\n",
3545 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3548 * Inform scsi mid-layer that we did reset and allow to handle
3549 * Unit Attention properly.
3551 scsi_report_bus_reset(hba->host, 0);
3553 hba->saved_uic_err = 0;
3555 ufshcd_clear_eh_in_progress(hba);
3558 scsi_unblock_requests(hba->host);
3559 ufshcd_release(hba);
3560 pm_runtime_put_sync(hba->dev);
3564 * ufshcd_update_uic_error - check and set fatal UIC error flags.
3565 * @hba: per-adapter instance
3567 static void ufshcd_update_uic_error(struct ufs_hba *hba)
3571 /* PA_INIT_ERROR is fatal and needs UIC reset */
3572 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
3573 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
3574 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
3576 /* UIC NL/TL/DME errors needs software retry */
3577 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
3579 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
3581 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
3583 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
3585 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
3587 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
3589 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
3590 __func__, hba->uic_error);
3594 * ufshcd_check_errors - Check for errors that need s/w attention
3595 * @hba: per-adapter instance
3597 static void ufshcd_check_errors(struct ufs_hba *hba)
3599 bool queue_eh_work = false;
3601 if (hba->errors & INT_FATAL_ERRORS)
3602 queue_eh_work = true;
3604 if (hba->errors & UIC_ERROR) {
3606 ufshcd_update_uic_error(hba);
3608 queue_eh_work = true;
3611 if (queue_eh_work) {
3612 /* handle fatal errors only when link is functional */
3613 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
3614 /* block commands from scsi mid-layer */
3615 scsi_block_requests(hba->host);
3617 /* transfer error masks to sticky bits */
3618 hba->saved_err |= hba->errors;
3619 hba->saved_uic_err |= hba->uic_error;
3621 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3622 schedule_work(&hba->eh_work);
3626 * if (!queue_eh_work) -
3627 * Other errors are either non-fatal where host recovers
3628 * itself without s/w intervention or errors that will be
3629 * handled by the SCSI core layer.
3634 * ufshcd_tmc_handler - handle task management function completion
3635 * @hba: per adapter instance
3637 static void ufshcd_tmc_handler(struct ufs_hba *hba)
3641 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
3642 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
3643 wake_up(&hba->tm_wq);
3647 * ufshcd_sl_intr - Interrupt service routine
3648 * @hba: per adapter instance
3649 * @intr_status: contains interrupts generated by the controller
3651 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
3653 hba->errors = UFSHCD_ERROR_MASK & intr_status;
3655 ufshcd_check_errors(hba);
3657 if (intr_status & UFSHCD_UIC_MASK)
3658 ufshcd_uic_cmd_compl(hba, intr_status);
3660 if (intr_status & UTP_TASK_REQ_COMPL)
3661 ufshcd_tmc_handler(hba);
3663 if (intr_status & UTP_TRANSFER_REQ_COMPL)
3664 ufshcd_transfer_req_compl(hba);
3668 * ufshcd_intr - Main interrupt service routine
3670 * @__hba: pointer to adapter instance
3672 * Returns IRQ_HANDLED - If interrupt is valid
3673 * IRQ_NONE - If invalid interrupt
3675 static irqreturn_t ufshcd_intr(int irq, void *__hba)
3678 irqreturn_t retval = IRQ_NONE;
3679 struct ufs_hba *hba = __hba;
3681 spin_lock(hba->host->host_lock);
3682 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
3685 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
3686 ufshcd_sl_intr(hba, intr_status);
3687 retval = IRQ_HANDLED;
3689 spin_unlock(hba->host->host_lock);
3693 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
3696 u32 mask = 1 << tag;
3697 unsigned long flags;
3699 if (!test_bit(tag, &hba->outstanding_tasks))
3702 spin_lock_irqsave(hba->host->host_lock, flags);
3703 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
3704 spin_unlock_irqrestore(hba->host->host_lock, flags);
3706 /* poll for max. 1 sec to clear door bell register by h/w */
3707 err = ufshcd_wait_for_register(hba,
3708 REG_UTP_TASK_REQ_DOOR_BELL,
3709 mask, 0, 1000, 1000);
3715 * ufshcd_issue_tm_cmd - issues task management commands to controller
3716 * @hba: per adapter instance
3717 * @lun_id: LUN ID to which TM command is sent
3718 * @task_id: task ID to which the TM command is applicable
3719 * @tm_function: task management function opcode
3720 * @tm_response: task management service response return value
3722 * Returns non-zero value on error, zero on success.
3724 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
3725 u8 tm_function, u8 *tm_response)
3727 struct utp_task_req_desc *task_req_descp;
3728 struct utp_upiu_task_req *task_req_upiup;
3729 struct Scsi_Host *host;
3730 unsigned long flags;
3738 * Get free slot, sleep if slots are unavailable.
3739 * Even though we use wait_event() which sleeps indefinitely,
3740 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
3742 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
3743 ufshcd_hold(hba, false);
3745 spin_lock_irqsave(host->host_lock, flags);
3746 task_req_descp = hba->utmrdl_base_addr;
3747 task_req_descp += free_slot;
3749 /* Configure task request descriptor */
3750 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
3751 task_req_descp->header.dword_2 =
3752 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
3754 /* Configure task request UPIU */
3756 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
3757 task_tag = hba->nutrs + free_slot;
3758 task_req_upiup->header.dword_0 =
3759 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
3761 task_req_upiup->header.dword_1 =
3762 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
3764 * The host shall provide the same value for LUN field in the basic
3765 * header and for Input Parameter.
3767 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
3768 task_req_upiup->input_param2 = cpu_to_be32(task_id);
3770 /* send command to the controller */
3771 __set_bit(free_slot, &hba->outstanding_tasks);
3772 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
3774 spin_unlock_irqrestore(host->host_lock, flags);
3776 /* wait until the task management command is completed */
3777 err = wait_event_timeout(hba->tm_wq,
3778 test_bit(free_slot, &hba->tm_condition),
3779 msecs_to_jiffies(TM_CMD_TIMEOUT));
3781 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
3782 __func__, tm_function);
3783 if (ufshcd_clear_tm_cmd(hba, free_slot))
3784 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
3785 __func__, free_slot);
3788 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
3791 clear_bit(free_slot, &hba->tm_condition);
3792 ufshcd_put_tm_slot(hba, free_slot);
3793 wake_up(&hba->tm_tag_wq);
3795 ufshcd_release(hba);
3800 * ufshcd_eh_device_reset_handler - device reset handler registered to
3802 * @cmd: SCSI command pointer
3804 * Returns SUCCESS/FAILED
3806 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
3808 struct Scsi_Host *host;
3809 struct ufs_hba *hba;
3814 struct ufshcd_lrb *lrbp;
3815 unsigned long flags;
3817 host = cmd->device->host;
3818 hba = shost_priv(host);
3819 tag = cmd->request->tag;
3821 lrbp = &hba->lrb[tag];
3822 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
3823 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3829 /* clear the commands that were pending for corresponding LUN */
3830 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
3831 if (hba->lrb[pos].lun == lrbp->lun) {
3832 err = ufshcd_clear_cmd(hba, pos);
3837 spin_lock_irqsave(host->host_lock, flags);
3838 ufshcd_transfer_req_compl(hba);
3839 spin_unlock_irqrestore(host->host_lock, flags);
3844 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
3851 * ufshcd_abort - abort a specific command
3852 * @cmd: SCSI command pointer
3854 * Abort the pending command in device by sending UFS_ABORT_TASK task management
3855 * command, and in host controller by clearing the door-bell register. There can
3856 * be race between controller sending the command to the device while abort is
3857 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
3858 * really issued and then try to abort it.
3860 * Returns SUCCESS/FAILED
3862 static int ufshcd_abort(struct scsi_cmnd *cmd)
3864 struct Scsi_Host *host;
3865 struct ufs_hba *hba;
3866 unsigned long flags;
3871 struct ufshcd_lrb *lrbp;
3874 host = cmd->device->host;
3875 hba = shost_priv(host);
3876 tag = cmd->request->tag;
3878 ufshcd_hold(hba, false);
3879 /* If command is already aborted/completed, return SUCCESS */
3880 if (!(test_bit(tag, &hba->outstanding_reqs)))
3883 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3884 if (!(reg & (1 << tag))) {
3886 "%s: cmd was completed, but without a notifying intr, tag = %d",
3890 lrbp = &hba->lrb[tag];
3891 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
3892 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
3893 UFS_QUERY_TASK, &resp);
3894 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
3895 /* cmd pending in the device */
3897 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3899 * cmd not pending in the device, check if it is
3902 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3903 if (reg & (1 << tag)) {
3904 /* sleep for max. 200us to stabilize */
3905 usleep_range(100, 200);
3908 /* command completed already */
3912 err = resp; /* service response error */
3922 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
3923 UFS_ABORT_TASK, &resp);
3924 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3926 err = resp; /* service response error */
3930 err = ufshcd_clear_cmd(hba, tag);
3934 scsi_dma_unmap(cmd);
3936 spin_lock_irqsave(host->host_lock, flags);
3937 __clear_bit(tag, &hba->outstanding_reqs);
3938 hba->lrb[tag].cmd = NULL;
3939 spin_unlock_irqrestore(host->host_lock, flags);
3941 clear_bit_unlock(tag, &hba->lrb_in_use);
3942 wake_up(&hba->dev_cmd.tag_wq);
3948 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
3953 * This ufshcd_release() corresponds to the original scsi cmd that got
3954 * aborted here (as we won't get any IRQ for it).
3956 ufshcd_release(hba);
3961 * ufshcd_host_reset_and_restore - reset and restore host controller
3962 * @hba: per-adapter instance
3964 * Note that host controller reset may issue DME_RESET to
3965 * local and remote (device) Uni-Pro stack and the attributes
3966 * are reset to default state.
3968 * Returns zero on success, non-zero on failure
3970 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
3973 unsigned long flags;
3975 /* Reset the host controller */
3976 spin_lock_irqsave(hba->host->host_lock, flags);
3977 ufshcd_hba_stop(hba);
3978 spin_unlock_irqrestore(hba->host->host_lock, flags);
3980 err = ufshcd_hba_enable(hba);
3984 /* Establish the link again and restore the device */
3985 err = ufshcd_probe_hba(hba);
3987 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
3991 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
3997 * ufshcd_reset_and_restore - reset and re-initialize host/device
3998 * @hba: per-adapter instance
4000 * Reset and recover device, host and re-establish link. This
4001 * is helpful to recover the communication in fatal error conditions.
4003 * Returns zero on success, non-zero on failure
4005 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4008 unsigned long flags;
4009 int retries = MAX_HOST_RESET_RETRIES;
4012 err = ufshcd_host_reset_and_restore(hba);
4013 } while (err && --retries);
4016 * After reset the door-bell might be cleared, complete
4017 * outstanding requests in s/w here.
4019 spin_lock_irqsave(hba->host->host_lock, flags);
4020 ufshcd_transfer_req_compl(hba);
4021 ufshcd_tmc_handler(hba);
4022 spin_unlock_irqrestore(hba->host->host_lock, flags);
4028 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4029 * @cmd - SCSI command pointer
4031 * Returns SUCCESS/FAILED
4033 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4036 unsigned long flags;
4037 struct ufs_hba *hba;
4039 hba = shost_priv(cmd->device->host);
4041 ufshcd_hold(hba, false);
4043 * Check if there is any race with fatal error handling.
4044 * If so, wait for it to complete. Even though fatal error
4045 * handling does reset and restore in some cases, don't assume
4046 * anything out of it. We are just avoiding race here.
4049 spin_lock_irqsave(hba->host->host_lock, flags);
4050 if (!(work_pending(&hba->eh_work) ||
4051 hba->ufshcd_state == UFSHCD_STATE_RESET))
4053 spin_unlock_irqrestore(hba->host->host_lock, flags);
4054 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4055 flush_work(&hba->eh_work);
4058 hba->ufshcd_state = UFSHCD_STATE_RESET;
4059 ufshcd_set_eh_in_progress(hba);
4060 spin_unlock_irqrestore(hba->host->host_lock, flags);
4062 err = ufshcd_reset_and_restore(hba);
4064 spin_lock_irqsave(hba->host->host_lock, flags);
4067 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4070 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4072 ufshcd_clear_eh_in_progress(hba);
4073 spin_unlock_irqrestore(hba->host->host_lock, flags);
4075 ufshcd_release(hba);
4080 * ufshcd_get_max_icc_level - calculate the ICC level
4081 * @sup_curr_uA: max. current supported by the regulator
4082 * @start_scan: row at the desc table to start scan from
4083 * @buff: power descriptor buffer
4085 * Returns calculated max ICC level for specific regulator
4087 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4094 for (i = start_scan; i >= 0; i--) {
4095 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4096 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4097 ATTR_ICC_LVL_UNIT_OFFSET;
4098 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4100 case UFSHCD_NANO_AMP:
4101 curr_uA = curr_uA / 1000;
4103 case UFSHCD_MILI_AMP:
4104 curr_uA = curr_uA * 1000;
4107 curr_uA = curr_uA * 1000 * 1000;
4109 case UFSHCD_MICRO_AMP:
4113 if (sup_curr_uA >= curr_uA)
4118 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4125 * ufshcd_calc_icc_level - calculate the max ICC level
4126 * In case regulators are not initialized we'll return 0
4127 * @hba: per-adapter instance
4128 * @desc_buf: power descriptor buffer to extract ICC levels from.
4129 * @len: length of desc_buff
4131 * Returns calculated ICC level
4133 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4134 u8 *desc_buf, int len)
4138 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4139 !hba->vreg_info.vccq2) {
4141 "%s: Regulator capability was not set, actvIccLevel=%d",
4142 __func__, icc_level);
4146 if (hba->vreg_info.vcc)
4147 icc_level = ufshcd_get_max_icc_level(
4148 hba->vreg_info.vcc->max_uA,
4149 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4150 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4152 if (hba->vreg_info.vccq)
4153 icc_level = ufshcd_get_max_icc_level(
4154 hba->vreg_info.vccq->max_uA,
4156 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4158 if (hba->vreg_info.vccq2)
4159 icc_level = ufshcd_get_max_icc_level(
4160 hba->vreg_info.vccq2->max_uA,
4162 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4167 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4170 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4171 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4173 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4176 "%s: Failed reading power descriptor.len = %d ret = %d",
4177 __func__, buff_len, ret);
4181 hba->init_prefetch_data.icc_level =
4182 ufshcd_find_max_sup_active_icc_level(hba,
4183 desc_buf, buff_len);
4184 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4185 __func__, hba->init_prefetch_data.icc_level);
4187 ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4188 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4189 &hba->init_prefetch_data.icc_level);
4193 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4194 __func__, hba->init_prefetch_data.icc_level , ret);
4199 * ufshcd_scsi_add_wlus - Adds required W-LUs
4200 * @hba: per-adapter instance
4202 * UFS device specification requires the UFS devices to support 4 well known
4204 * "REPORT_LUNS" (address: 01h)
4205 * "UFS Device" (address: 50h)
4206 * "RPMB" (address: 44h)
4207 * "BOOT" (address: 30h)
4208 * UFS device's power management needs to be controlled by "POWER CONDITION"
4209 * field of SSU (START STOP UNIT) command. But this "power condition" field
4210 * will take effect only when its sent to "UFS device" well known logical unit
4211 * hence we require the scsi_device instance to represent this logical unit in
4212 * order for the UFS host driver to send the SSU command for power management.
4214 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4215 * Block) LU so user space process can control this LU. User space may also
4216 * want to have access to BOOT LU.
4218 * This function adds scsi device instances for each of all well known LUs
4219 * (except "REPORT LUNS" LU).
4221 * Returns zero on success (all required W-LUs are added successfully),
4222 * non-zero error value on failure (if failed to add any of the required W-LU).
4224 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4227 struct scsi_device *sdev_rpmb;
4228 struct scsi_device *sdev_boot;
4230 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4231 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4232 if (IS_ERR(hba->sdev_ufs_device)) {
4233 ret = PTR_ERR(hba->sdev_ufs_device);
4234 hba->sdev_ufs_device = NULL;
4237 scsi_device_put(hba->sdev_ufs_device);
4239 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4240 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4241 if (IS_ERR(sdev_boot)) {
4242 ret = PTR_ERR(sdev_boot);
4243 goto remove_sdev_ufs_device;
4245 scsi_device_put(sdev_boot);
4247 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4248 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4249 if (IS_ERR(sdev_rpmb)) {
4250 ret = PTR_ERR(sdev_rpmb);
4251 goto remove_sdev_boot;
4253 scsi_device_put(sdev_rpmb);
4257 scsi_remove_device(sdev_boot);
4258 remove_sdev_ufs_device:
4259 scsi_remove_device(hba->sdev_ufs_device);
4265 * ufshcd_probe_hba - probe hba to detect device and initialize
4266 * @hba: per-adapter instance
4268 * Execute link-startup and verify device initialization
4270 static int ufshcd_probe_hba(struct ufs_hba *hba)
4274 ret = ufshcd_link_startup(hba);
4278 ufshcd_init_pwr_info(hba);
4280 /* UniPro link is active now */
4281 ufshcd_set_link_active(hba);
4283 ret = ufshcd_verify_dev_init(hba);
4287 ret = ufshcd_complete_dev_init(hba);
4291 /* UFS device is also active now */
4292 ufshcd_set_ufs_dev_active(hba);
4293 ufshcd_force_reset_auto_bkops(hba);
4294 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4295 hba->wlun_dev_clr_ua = true;
4297 if (ufshcd_get_max_pwr_mode(hba)) {
4299 "%s: Failed getting max supported power mode\n",
4302 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4304 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4309 * If we are in error handling context or in power management callbacks
4310 * context, no need to scan the host
4312 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4315 /* clear any previous UFS device information */
4316 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
4317 if (!ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4318 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
4319 hba->dev_info.f_power_on_wp_en = flag;
4321 if (!hba->is_init_prefetch)
4322 ufshcd_init_icc_levels(hba);
4324 /* Add required well known logical units to scsi mid layer */
4325 if (ufshcd_scsi_add_wlus(hba))
4328 scsi_scan_host(hba->host);
4329 pm_runtime_put_sync(hba->dev);
4332 if (!hba->is_init_prefetch)
4333 hba->is_init_prefetch = true;
4335 /* Resume devfreq after UFS device is detected */
4336 if (ufshcd_is_clkscaling_enabled(hba))
4337 devfreq_resume_device(hba->devfreq);
4341 * If we failed to initialize the device or the device is not
4342 * present, turn off the power/clocks etc.
4344 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4345 pm_runtime_put_sync(hba->dev);
4346 ufshcd_hba_exit(hba);
4353 * ufshcd_async_scan - asynchronous execution for probing hba
4354 * @data: data pointer to pass to this function
4355 * @cookie: cookie data
4357 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4359 struct ufs_hba *hba = (struct ufs_hba *)data;
4361 ufshcd_probe_hba(hba);
4364 static struct scsi_host_template ufshcd_driver_template = {
4365 .module = THIS_MODULE,
4367 .proc_name = UFSHCD,
4368 .queuecommand = ufshcd_queuecommand,
4369 .slave_alloc = ufshcd_slave_alloc,
4370 .slave_configure = ufshcd_slave_configure,
4371 .slave_destroy = ufshcd_slave_destroy,
4372 .change_queue_depth = ufshcd_change_queue_depth,
4373 .eh_abort_handler = ufshcd_abort,
4374 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4375 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
4377 .sg_tablesize = SG_ALL,
4378 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
4379 .can_queue = UFSHCD_CAN_QUEUE,
4380 .max_host_blocked = 1,
4381 .track_queue_depth = 1,
4384 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4392 ret = regulator_set_load(vreg->reg, ua);
4394 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4395 __func__, vreg->name, ua, ret);
4401 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
4402 struct ufs_vreg *vreg)
4404 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
4407 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
4408 struct ufs_vreg *vreg)
4410 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
4413 static int ufshcd_config_vreg(struct device *dev,
4414 struct ufs_vreg *vreg, bool on)
4417 struct regulator *reg = vreg->reg;
4418 const char *name = vreg->name;
4419 int min_uV, uA_load;
4423 if (regulator_count_voltages(reg) > 0) {
4424 min_uV = on ? vreg->min_uV : 0;
4425 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
4427 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
4428 __func__, name, ret);
4432 uA_load = on ? vreg->max_uA : 0;
4433 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
4441 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
4445 if (!vreg || vreg->enabled)
4448 ret = ufshcd_config_vreg(dev, vreg, true);
4450 ret = regulator_enable(vreg->reg);
4453 vreg->enabled = true;
4455 dev_err(dev, "%s: %s enable failed, err=%d\n",
4456 __func__, vreg->name, ret);
4461 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
4465 if (!vreg || !vreg->enabled)
4468 ret = regulator_disable(vreg->reg);
4471 /* ignore errors on applying disable config */
4472 ufshcd_config_vreg(dev, vreg, false);
4473 vreg->enabled = false;
4475 dev_err(dev, "%s: %s disable failed, err=%d\n",
4476 __func__, vreg->name, ret);
4482 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
4485 struct device *dev = hba->dev;
4486 struct ufs_vreg_info *info = &hba->vreg_info;
4491 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
4495 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
4499 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
4505 ufshcd_toggle_vreg(dev, info->vccq2, false);
4506 ufshcd_toggle_vreg(dev, info->vccq, false);
4507 ufshcd_toggle_vreg(dev, info->vcc, false);
4512 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
4514 struct ufs_vreg_info *info = &hba->vreg_info;
4517 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
4522 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
4529 vreg->reg = devm_regulator_get(dev, vreg->name);
4530 if (IS_ERR(vreg->reg)) {
4531 ret = PTR_ERR(vreg->reg);
4532 dev_err(dev, "%s: %s get failed, err=%d\n",
4533 __func__, vreg->name, ret);
4539 static int ufshcd_init_vreg(struct ufs_hba *hba)
4542 struct device *dev = hba->dev;
4543 struct ufs_vreg_info *info = &hba->vreg_info;
4548 ret = ufshcd_get_vreg(dev, info->vcc);
4552 ret = ufshcd_get_vreg(dev, info->vccq);
4556 ret = ufshcd_get_vreg(dev, info->vccq2);
4561 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
4563 struct ufs_vreg_info *info = &hba->vreg_info;
4566 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
4571 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
4575 struct ufs_clk_info *clki;
4576 struct list_head *head = &hba->clk_list_head;
4577 unsigned long flags;
4579 if (!head || list_empty(head))
4582 list_for_each_entry(clki, head, list) {
4583 if (!IS_ERR_OR_NULL(clki->clk)) {
4584 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
4587 if (on && !clki->enabled) {
4588 ret = clk_prepare_enable(clki->clk);
4590 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
4591 __func__, clki->name, ret);
4594 } else if (!on && clki->enabled) {
4595 clk_disable_unprepare(clki->clk);
4598 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
4599 clki->name, on ? "en" : "dis");
4603 ret = ufshcd_vops_setup_clocks(hba, on);
4606 list_for_each_entry(clki, head, list) {
4607 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
4608 clk_disable_unprepare(clki->clk);
4611 spin_lock_irqsave(hba->host->host_lock, flags);
4612 hba->clk_gating.state = CLKS_ON;
4613 spin_unlock_irqrestore(hba->host->host_lock, flags);
4618 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
4620 return __ufshcd_setup_clocks(hba, on, false);
4623 static int ufshcd_init_clocks(struct ufs_hba *hba)
4626 struct ufs_clk_info *clki;
4627 struct device *dev = hba->dev;
4628 struct list_head *head = &hba->clk_list_head;
4630 if (!head || list_empty(head))
4633 list_for_each_entry(clki, head, list) {
4637 clki->clk = devm_clk_get(dev, clki->name);
4638 if (IS_ERR(clki->clk)) {
4639 ret = PTR_ERR(clki->clk);
4640 dev_err(dev, "%s: %s clk get failed, %d\n",
4641 __func__, clki->name, ret);
4645 if (clki->max_freq) {
4646 ret = clk_set_rate(clki->clk, clki->max_freq);
4648 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
4649 __func__, clki->name,
4650 clki->max_freq, ret);
4653 clki->curr_freq = clki->max_freq;
4655 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
4656 clki->name, clk_get_rate(clki->clk));
4662 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
4669 err = ufshcd_vops_init(hba);
4673 err = ufshcd_vops_setup_regulators(hba, true);
4680 ufshcd_vops_exit(hba);
4683 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
4684 __func__, ufshcd_get_var_name(hba), err);
4688 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
4693 ufshcd_vops_setup_clocks(hba, false);
4695 ufshcd_vops_setup_regulators(hba, false);
4697 ufshcd_vops_exit(hba);
4700 static int ufshcd_hba_init(struct ufs_hba *hba)
4705 * Handle host controller power separately from the UFS device power
4706 * rails as it will help controlling the UFS host controller power
4707 * collapse easily which is different than UFS device power collapse.
4708 * Also, enable the host controller power before we go ahead with rest
4709 * of the initialization here.
4711 err = ufshcd_init_hba_vreg(hba);
4715 err = ufshcd_setup_hba_vreg(hba, true);
4719 err = ufshcd_init_clocks(hba);
4721 goto out_disable_hba_vreg;
4723 err = ufshcd_setup_clocks(hba, true);
4725 goto out_disable_hba_vreg;
4727 err = ufshcd_init_vreg(hba);
4729 goto out_disable_clks;
4731 err = ufshcd_setup_vreg(hba, true);
4733 goto out_disable_clks;
4735 err = ufshcd_variant_hba_init(hba);
4737 goto out_disable_vreg;
4739 hba->is_powered = true;
4743 ufshcd_setup_vreg(hba, false);
4745 ufshcd_setup_clocks(hba, false);
4746 out_disable_hba_vreg:
4747 ufshcd_setup_hba_vreg(hba, false);
4752 static void ufshcd_hba_exit(struct ufs_hba *hba)
4754 if (hba->is_powered) {
4755 ufshcd_variant_hba_exit(hba);
4756 ufshcd_setup_vreg(hba, false);
4757 ufshcd_setup_clocks(hba, false);
4758 ufshcd_setup_hba_vreg(hba, false);
4759 hba->is_powered = false;
4764 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
4766 unsigned char cmd[6] = {REQUEST_SENSE,
4770 SCSI_SENSE_BUFFERSIZE,
4775 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
4781 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
4782 SCSI_SENSE_BUFFERSIZE, NULL,
4783 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
4785 pr_err("%s: failed with err %d\n", __func__, ret);
4793 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
4795 * @hba: per adapter instance
4796 * @pwr_mode: device power mode to set
4798 * Returns 0 if requested power mode is set successfully
4799 * Returns non-zero if failed to set the requested power mode
4801 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
4802 enum ufs_dev_pwr_mode pwr_mode)
4804 unsigned char cmd[6] = { START_STOP };
4805 struct scsi_sense_hdr sshdr;
4806 struct scsi_device *sdp;
4807 unsigned long flags;
4810 spin_lock_irqsave(hba->host->host_lock, flags);
4811 sdp = hba->sdev_ufs_device;
4813 ret = scsi_device_get(sdp);
4814 if (!ret && !scsi_device_online(sdp)) {
4816 scsi_device_put(sdp);
4821 spin_unlock_irqrestore(hba->host->host_lock, flags);
4827 * If scsi commands fail, the scsi mid-layer schedules scsi error-
4828 * handling, which would wait for host to be resumed. Since we know
4829 * we are functional while we are here, skip host resume in error
4832 hba->host->eh_noresume = 1;
4833 if (hba->wlun_dev_clr_ua) {
4834 ret = ufshcd_send_request_sense(hba, sdp);
4837 /* Unit attention condition is cleared now */
4838 hba->wlun_dev_clr_ua = false;
4841 cmd[4] = pwr_mode << 4;
4844 * Current function would be generally called from the power management
4845 * callbacks hence set the REQ_PM flag so that it doesn't resume the
4846 * already suspended childs.
4848 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
4849 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
4851 sdev_printk(KERN_WARNING, sdp,
4852 "START_STOP failed for power mode: %d, result %x\n",
4854 if (driver_byte(ret) & DRIVER_SENSE)
4855 scsi_print_sense_hdr(sdp, NULL, &sshdr);
4859 hba->curr_dev_pwr_mode = pwr_mode;
4861 scsi_device_put(sdp);
4862 hba->host->eh_noresume = 0;
4866 static int ufshcd_link_state_transition(struct ufs_hba *hba,
4867 enum uic_link_state req_link_state,
4868 int check_for_bkops)
4872 if (req_link_state == hba->uic_link_state)
4875 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
4876 ret = ufshcd_uic_hibern8_enter(hba);
4878 ufshcd_set_link_hibern8(hba);
4883 * If autobkops is enabled, link can't be turned off because
4884 * turning off the link would also turn off the device.
4886 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
4887 (!check_for_bkops || (check_for_bkops &&
4888 !hba->auto_bkops_enabled))) {
4890 * Change controller state to "reset state" which
4891 * should also put the link in off/reset state
4893 ufshcd_hba_stop(hba);
4895 * TODO: Check if we need any delay to make sure that
4896 * controller is reset
4898 ufshcd_set_link_off(hba);
4905 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
4908 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
4911 * If UFS device and link is in OFF state, all power supplies (VCC,
4912 * VCCQ, VCCQ2) can be turned off if power on write protect is not
4913 * required. If UFS link is inactive (Hibern8 or OFF state) and device
4914 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
4916 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
4917 * in low power state which would save some power.
4919 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
4920 !hba->dev_info.is_lu_power_on_wp) {
4921 ufshcd_setup_vreg(hba, false);
4922 } else if (!ufshcd_is_ufs_dev_active(hba)) {
4923 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
4924 if (!ufshcd_is_link_active(hba)) {
4925 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
4926 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
4931 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
4935 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
4936 !hba->dev_info.is_lu_power_on_wp) {
4937 ret = ufshcd_setup_vreg(hba, true);
4938 } else if (!ufshcd_is_ufs_dev_active(hba)) {
4939 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
4940 if (!ret && !ufshcd_is_link_active(hba)) {
4941 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
4944 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
4952 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
4954 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
4959 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
4961 if (ufshcd_is_link_off(hba))
4962 ufshcd_setup_hba_vreg(hba, false);
4965 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
4967 if (ufshcd_is_link_off(hba))
4968 ufshcd_setup_hba_vreg(hba, true);
4972 * ufshcd_suspend - helper function for suspend operations
4973 * @hba: per adapter instance
4974 * @pm_op: desired low power operation type
4976 * This function will try to put the UFS device and link into low power
4977 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
4978 * (System PM level).
4980 * If this function is called during shutdown, it will make sure that
4981 * both UFS device and UFS link is powered off.
4983 * NOTE: UFS device & link must be active before we enter in this function.
4985 * Returns 0 for success and non-zero for failure
4987 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
4990 enum ufs_pm_level pm_lvl;
4991 enum ufs_dev_pwr_mode req_dev_pwr_mode;
4992 enum uic_link_state req_link_state;
4994 hba->pm_op_in_progress = 1;
4995 if (!ufshcd_is_shutdown_pm(pm_op)) {
4996 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
4997 hba->rpm_lvl : hba->spm_lvl;
4998 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
4999 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5001 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5002 req_link_state = UIC_LINK_OFF_STATE;
5006 * If we can't transition into any of the low power modes
5007 * just gate the clocks.
5009 ufshcd_hold(hba, false);
5010 hba->clk_gating.is_suspended = true;
5012 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5013 req_link_state == UIC_LINK_ACTIVE_STATE) {
5017 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5018 (req_link_state == hba->uic_link_state))
5021 /* UFS device & link must be active before we enter in this function */
5022 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5027 if (ufshcd_is_runtime_pm(pm_op)) {
5028 if (ufshcd_can_autobkops_during_suspend(hba)) {
5030 * The device is idle with no requests in the queue,
5031 * allow background operations if bkops status shows
5032 * that performance might be impacted.
5034 ret = ufshcd_urgent_bkops(hba);
5038 /* make sure that auto bkops is disabled */
5039 ufshcd_disable_auto_bkops(hba);
5043 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5044 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5045 !ufshcd_is_runtime_pm(pm_op))) {
5046 /* ensure that bkops is disabled */
5047 ufshcd_disable_auto_bkops(hba);
5048 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5053 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5055 goto set_dev_active;
5057 ufshcd_vreg_set_lpm(hba);
5061 * The clock scaling needs access to controller registers. Hence, Wait
5062 * for pending clock scaling work to be done before clocks are
5065 if (ufshcd_is_clkscaling_enabled(hba)) {
5066 devfreq_suspend_device(hba->devfreq);
5067 hba->clk_scaling.window_start_t = 0;
5070 * Call vendor specific suspend callback. As these callbacks may access
5071 * vendor specific host controller register space call them before the
5072 * host clocks are ON.
5074 ret = ufshcd_vops_suspend(hba, pm_op);
5076 goto set_link_active;
5078 ret = ufshcd_vops_setup_clocks(hba, false);
5082 if (!ufshcd_is_link_active(hba))
5083 ufshcd_setup_clocks(hba, false);
5085 /* If link is active, device ref_clk can't be switched off */
5086 __ufshcd_setup_clocks(hba, false, true);
5088 hba->clk_gating.state = CLKS_OFF;
5090 * Disable the host irq as host controller as there won't be any
5091 * host controller transaction expected till resume.
5093 ufshcd_disable_irq(hba);
5094 /* Put the host controller in low power mode if possible */
5095 ufshcd_hba_vreg_set_lpm(hba);
5099 ufshcd_vops_resume(hba, pm_op);
5101 ufshcd_vreg_set_hpm(hba);
5102 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5103 ufshcd_set_link_active(hba);
5104 else if (ufshcd_is_link_off(hba))
5105 ufshcd_host_reset_and_restore(hba);
5107 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5108 ufshcd_disable_auto_bkops(hba);
5110 hba->clk_gating.is_suspended = false;
5111 ufshcd_release(hba);
5113 hba->pm_op_in_progress = 0;
5118 * ufshcd_resume - helper function for resume operations
5119 * @hba: per adapter instance
5120 * @pm_op: runtime PM or system PM
5122 * This function basically brings the UFS device, UniPro link and controller
5125 * Returns 0 for success and non-zero for failure
5127 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5130 enum uic_link_state old_link_state;
5132 hba->pm_op_in_progress = 1;
5133 old_link_state = hba->uic_link_state;
5135 ufshcd_hba_vreg_set_hpm(hba);
5136 /* Make sure clocks are enabled before accessing controller */
5137 ret = ufshcd_setup_clocks(hba, true);
5141 /* enable the host irq as host controller would be active soon */
5142 ret = ufshcd_enable_irq(hba);
5144 goto disable_irq_and_vops_clks;
5146 ret = ufshcd_vreg_set_hpm(hba);
5148 goto disable_irq_and_vops_clks;
5151 * Call vendor specific resume callback. As these callbacks may access
5152 * vendor specific host controller register space call them when the
5153 * host clocks are ON.
5155 ret = ufshcd_vops_resume(hba, pm_op);
5159 if (ufshcd_is_link_hibern8(hba)) {
5160 ret = ufshcd_uic_hibern8_exit(hba);
5162 ufshcd_set_link_active(hba);
5164 goto vendor_suspend;
5165 } else if (ufshcd_is_link_off(hba)) {
5166 ret = ufshcd_host_reset_and_restore(hba);
5168 * ufshcd_host_reset_and_restore() should have already
5169 * set the link state as active
5171 if (ret || !ufshcd_is_link_active(hba))
5172 goto vendor_suspend;
5175 if (!ufshcd_is_ufs_dev_active(hba)) {
5176 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5178 goto set_old_link_state;
5182 * If BKOPs operations are urgently needed at this moment then
5183 * keep auto-bkops enabled or else disable it.
5185 ufshcd_urgent_bkops(hba);
5186 hba->clk_gating.is_suspended = false;
5188 if (ufshcd_is_clkscaling_enabled(hba))
5189 devfreq_resume_device(hba->devfreq);
5191 /* Schedule clock gating in case of no access to UFS device yet */
5192 ufshcd_release(hba);
5196 ufshcd_link_state_transition(hba, old_link_state, 0);
5198 ufshcd_vops_suspend(hba, pm_op);
5200 ufshcd_vreg_set_lpm(hba);
5201 disable_irq_and_vops_clks:
5202 ufshcd_disable_irq(hba);
5203 ufshcd_setup_clocks(hba, false);
5205 hba->pm_op_in_progress = 0;
5210 * ufshcd_system_suspend - system suspend routine
5211 * @hba: per adapter instance
5212 * @pm_op: runtime PM or system PM
5214 * Check the description of ufshcd_suspend() function for more details.
5216 * Returns 0 for success and non-zero for failure
5218 int ufshcd_system_suspend(struct ufs_hba *hba)
5222 if (!hba || !hba->is_powered)
5225 if (pm_runtime_suspended(hba->dev)) {
5226 if (hba->rpm_lvl == hba->spm_lvl)
5228 * There is possibility that device may still be in
5229 * active state during the runtime suspend.
5231 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5232 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5236 * UFS device and/or UFS link low power states during runtime
5237 * suspend seems to be different than what is expected during
5238 * system suspend. Hence runtime resume the devic & link and
5239 * let the system suspend low power states to take effect.
5240 * TODO: If resume takes longer time, we might have optimize
5241 * it in future by not resuming everything if possible.
5243 ret = ufshcd_runtime_resume(hba);
5248 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5251 hba->is_sys_suspended = true;
5254 EXPORT_SYMBOL(ufshcd_system_suspend);
5257 * ufshcd_system_resume - system resume routine
5258 * @hba: per adapter instance
5260 * Returns 0 for success and non-zero for failure
5263 int ufshcd_system_resume(struct ufs_hba *hba)
5265 if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5267 * Let the runtime resume take care of resuming
5268 * if runtime suspended.
5272 return ufshcd_resume(hba, UFS_SYSTEM_PM);
5274 EXPORT_SYMBOL(ufshcd_system_resume);
5277 * ufshcd_runtime_suspend - runtime suspend routine
5278 * @hba: per adapter instance
5280 * Check the description of ufshcd_suspend() function for more details.
5282 * Returns 0 for success and non-zero for failure
5284 int ufshcd_runtime_suspend(struct ufs_hba *hba)
5286 if (!hba || !hba->is_powered)
5289 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
5291 EXPORT_SYMBOL(ufshcd_runtime_suspend);
5294 * ufshcd_runtime_resume - runtime resume routine
5295 * @hba: per adapter instance
5297 * This function basically brings the UFS device, UniPro link and controller
5298 * to active state. Following operations are done in this function:
5300 * 1. Turn on all the controller related clocks
5301 * 2. Bring the UniPro link out of Hibernate state
5302 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5304 * 4. If auto-bkops is enabled on the device, disable it.
5306 * So following would be the possible power state after this function return
5308 * S1: UFS device in Active state with VCC rail ON
5309 * UniPro link in Active state
5310 * All the UFS/UniPro controller clocks are ON
5312 * Returns 0 for success and non-zero for failure
5314 int ufshcd_runtime_resume(struct ufs_hba *hba)
5316 if (!hba || !hba->is_powered)
5319 return ufshcd_resume(hba, UFS_RUNTIME_PM);
5321 EXPORT_SYMBOL(ufshcd_runtime_resume);
5323 int ufshcd_runtime_idle(struct ufs_hba *hba)
5327 EXPORT_SYMBOL(ufshcd_runtime_idle);
5330 * ufshcd_shutdown - shutdown routine
5331 * @hba: per adapter instance
5333 * This function would power off both UFS device and UFS link.
5335 * Returns 0 always to allow force shutdown even in case of errors.
5337 int ufshcd_shutdown(struct ufs_hba *hba)
5341 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5344 if (pm_runtime_suspended(hba->dev)) {
5345 ret = ufshcd_runtime_resume(hba);
5350 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5353 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5354 /* allow force shutdown even in case of errors */
5357 EXPORT_SYMBOL(ufshcd_shutdown);
5360 * Values permitted 0, 1, 2.
5361 * 0 -> Disable IO latency histograms (default)
5362 * 1 -> Enable IO latency histograms
5363 * 2 -> Zero out IO latency histograms
5366 latency_hist_store(struct device *dev, struct device_attribute *attr,
5367 const char *buf, size_t count)
5369 struct ufs_hba *hba = dev_get_drvdata(dev);
5372 if (kstrtol(buf, 0, &value))
5374 if (value == BLK_IO_LAT_HIST_ZERO)
5375 blk_zero_latency_hist(&hba->io_lat_s);
5376 else if (value == BLK_IO_LAT_HIST_ENABLE ||
5377 value == BLK_IO_LAT_HIST_DISABLE)
5378 hba->latency_hist_enabled = value;
5383 latency_hist_show(struct device *dev, struct device_attribute *attr,
5386 struct ufs_hba *hba = dev_get_drvdata(dev);
5388 return blk_latency_hist_show(&hba->io_lat_s, buf);
5391 static DEVICE_ATTR(latency_hist, S_IRUGO | S_IWUSR,
5392 latency_hist_show, latency_hist_store);
5395 ufshcd_init_latency_hist(struct ufs_hba *hba)
5397 if (device_create_file(hba->dev, &dev_attr_latency_hist))
5398 dev_err(hba->dev, "Failed to create latency_hist sysfs entry\n");
5402 ufshcd_exit_latency_hist(struct ufs_hba *hba)
5404 device_create_file(hba->dev, &dev_attr_latency_hist);
5408 * ufshcd_remove - de-allocate SCSI host and host memory space
5409 * data structure memory
5410 * @hba - per adapter instance
5412 void ufshcd_remove(struct ufs_hba *hba)
5414 scsi_remove_host(hba->host);
5415 /* disable interrupts */
5416 ufshcd_disable_intr(hba, hba->intr_mask);
5417 ufshcd_hba_stop(hba);
5419 scsi_host_put(hba->host);
5421 ufshcd_exit_clk_gating(hba);
5422 ufshcd_exit_latency_hist(hba);
5423 if (ufshcd_is_clkscaling_enabled(hba))
5424 devfreq_remove_device(hba->devfreq);
5425 ufshcd_hba_exit(hba);
5427 EXPORT_SYMBOL_GPL(ufshcd_remove);
5430 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
5431 * @hba: pointer to Host Bus Adapter (HBA)
5433 void ufshcd_dealloc_host(struct ufs_hba *hba)
5435 scsi_host_put(hba->host);
5437 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
5440 * ufshcd_set_dma_mask - Set dma mask based on the controller
5441 * addressing capability
5442 * @hba: per adapter instance
5444 * Returns 0 for success, non-zero for failure
5446 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
5448 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
5449 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
5452 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
5456 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
5457 * @dev: pointer to device handle
5458 * @hba_handle: driver private handle
5459 * Returns 0 on success, non-zero value on failure
5461 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
5463 struct Scsi_Host *host;
5464 struct ufs_hba *hba;
5469 "Invalid memory reference for dev is NULL\n");
5474 host = scsi_host_alloc(&ufshcd_driver_template,
5475 sizeof(struct ufs_hba));
5477 dev_err(dev, "scsi_host_alloc failed\n");
5481 hba = shost_priv(host);
5489 EXPORT_SYMBOL(ufshcd_alloc_host);
5491 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
5494 struct ufs_clk_info *clki;
5495 struct list_head *head = &hba->clk_list_head;
5497 if (!head || list_empty(head))
5500 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
5504 list_for_each_entry(clki, head, list) {
5505 if (!IS_ERR_OR_NULL(clki->clk)) {
5506 if (scale_up && clki->max_freq) {
5507 if (clki->curr_freq == clki->max_freq)
5509 ret = clk_set_rate(clki->clk, clki->max_freq);
5511 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5512 __func__, clki->name,
5513 clki->max_freq, ret);
5516 clki->curr_freq = clki->max_freq;
5518 } else if (!scale_up && clki->min_freq) {
5519 if (clki->curr_freq == clki->min_freq)
5521 ret = clk_set_rate(clki->clk, clki->min_freq);
5523 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5524 __func__, clki->name,
5525 clki->min_freq, ret);
5528 clki->curr_freq = clki->min_freq;
5531 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
5532 clki->name, clk_get_rate(clki->clk));
5535 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
5541 static int ufshcd_devfreq_target(struct device *dev,
5542 unsigned long *freq, u32 flags)
5545 struct ufs_hba *hba = dev_get_drvdata(dev);
5547 if (!ufshcd_is_clkscaling_enabled(hba))
5550 if (*freq == UINT_MAX)
5551 err = ufshcd_scale_clks(hba, true);
5552 else if (*freq == 0)
5553 err = ufshcd_scale_clks(hba, false);
5558 static int ufshcd_devfreq_get_dev_status(struct device *dev,
5559 struct devfreq_dev_status *stat)
5561 struct ufs_hba *hba = dev_get_drvdata(dev);
5562 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
5563 unsigned long flags;
5565 if (!ufshcd_is_clkscaling_enabled(hba))
5568 memset(stat, 0, sizeof(*stat));
5570 spin_lock_irqsave(hba->host->host_lock, flags);
5571 if (!scaling->window_start_t)
5574 if (scaling->is_busy_started)
5575 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
5576 scaling->busy_start_t));
5578 stat->total_time = jiffies_to_usecs((long)jiffies -
5579 (long)scaling->window_start_t);
5580 stat->busy_time = scaling->tot_busy_t;
5582 scaling->window_start_t = jiffies;
5583 scaling->tot_busy_t = 0;
5585 if (hba->outstanding_reqs) {
5586 scaling->busy_start_t = ktime_get();
5587 scaling->is_busy_started = true;
5589 scaling->busy_start_t = ktime_set(0, 0);
5590 scaling->is_busy_started = false;
5592 spin_unlock_irqrestore(hba->host->host_lock, flags);
5596 static struct devfreq_dev_profile ufs_devfreq_profile = {
5598 .target = ufshcd_devfreq_target,
5599 .get_dev_status = ufshcd_devfreq_get_dev_status,
5603 * ufshcd_init - Driver initialization routine
5604 * @hba: per-adapter instance
5605 * @mmio_base: base register address
5606 * @irq: Interrupt line of device
5607 * Returns 0 on success, non-zero value on failure
5609 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
5612 struct Scsi_Host *host = hba->host;
5613 struct device *dev = hba->dev;
5617 "Invalid memory reference for mmio_base is NULL\n");
5622 hba->mmio_base = mmio_base;
5625 err = ufshcd_hba_init(hba);
5629 /* Read capabilities registers */
5630 ufshcd_hba_capabilities(hba);
5632 /* Get UFS version supported by the controller */
5633 hba->ufs_version = ufshcd_get_ufs_version(hba);
5635 /* Get Interrupt bit mask per version */
5636 hba->intr_mask = ufshcd_get_intr_mask(hba);
5638 err = ufshcd_set_dma_mask(hba);
5640 dev_err(hba->dev, "set dma mask failed\n");
5644 /* Allocate memory for host memory space */
5645 err = ufshcd_memory_alloc(hba);
5647 dev_err(hba->dev, "Memory allocation failed\n");
5652 ufshcd_host_memory_configure(hba);
5654 host->can_queue = hba->nutrs;
5655 host->cmd_per_lun = hba->nutrs;
5656 host->max_id = UFSHCD_MAX_ID;
5657 host->max_lun = UFS_MAX_LUNS;
5658 host->max_channel = UFSHCD_MAX_CHANNEL;
5659 host->unique_id = host->host_no;
5660 host->max_cmd_len = MAX_CDB_SIZE;
5662 hba->max_pwr_info.is_valid = false;
5664 /* Initailize wait queue for task management */
5665 init_waitqueue_head(&hba->tm_wq);
5666 init_waitqueue_head(&hba->tm_tag_wq);
5668 /* Initialize work queues */
5669 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
5670 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
5672 /* Initialize UIC command mutex */
5673 mutex_init(&hba->uic_cmd_mutex);
5675 /* Initialize mutex for device management commands */
5676 mutex_init(&hba->dev_cmd.lock);
5678 /* Initialize device management tag acquire wait queue */
5679 init_waitqueue_head(&hba->dev_cmd.tag_wq);
5681 ufshcd_init_clk_gating(hba);
5682 /* IRQ registration */
5683 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
5685 dev_err(hba->dev, "request irq failed\n");
5688 hba->is_irq_enabled = true;
5691 err = scsi_add_host(host, hba->dev);
5693 dev_err(hba->dev, "scsi_add_host failed\n");
5697 /* Host controller enable */
5698 err = ufshcd_hba_enable(hba);
5700 dev_err(hba->dev, "Host controller enable failed\n");
5701 goto out_remove_scsi_host;
5704 if (ufshcd_is_clkscaling_enabled(hba)) {
5705 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
5706 "simple_ondemand", NULL);
5707 if (IS_ERR(hba->devfreq)) {
5708 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
5709 PTR_ERR(hba->devfreq));
5710 goto out_remove_scsi_host;
5712 /* Suspend devfreq until the UFS device is detected */
5713 devfreq_suspend_device(hba->devfreq);
5714 hba->clk_scaling.window_start_t = 0;
5717 /* Hold auto suspend until async scan completes */
5718 pm_runtime_get_sync(dev);
5720 ufshcd_init_latency_hist(hba);
5723 * The device-initialize-sequence hasn't been invoked yet.
5724 * Set the device to power-off state
5726 ufshcd_set_ufs_dev_poweroff(hba);
5728 async_schedule(ufshcd_async_scan, hba);
5732 out_remove_scsi_host:
5733 scsi_remove_host(hba->host);
5735 ufshcd_exit_clk_gating(hba);
5736 ufshcd_exit_latency_hist(hba);
5738 hba->is_irq_enabled = false;
5739 scsi_host_put(host);
5740 ufshcd_hba_exit(hba);
5744 EXPORT_SYMBOL_GPL(ufshcd_init);
5746 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
5747 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
5748 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
5749 MODULE_LICENSE("GPL");
5750 MODULE_VERSION(UFSHCD_DRIVER_VERSION);