2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
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 * Query request timeout for fDeviceInit flag
64 * fDeviceInit query response time for some devices is too large that default
65 * QUERY_REQ_TIMEOUT may not be enough for such devices.
67 #define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
69 /* Task management command timeout */
70 #define TM_CMD_TIMEOUT 100 /* msecs */
72 /* maximum number of retries for a general UIC command */
73 #define UFS_UIC_COMMAND_RETRIES 3
75 /* maximum number of link-startup retries */
76 #define DME_LINKSTARTUP_RETRIES 3
78 /* Maximum retries for Hibern8 enter */
79 #define UIC_HIBERN8_ENTER_RETRIES 3
81 /* maximum number of reset retries before giving up */
82 #define MAX_HOST_RESET_RETRIES 5
84 /* Expose the flag value from utp_upiu_query.value */
85 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
87 /* Interrupt aggregation default timeout, unit: 40us */
88 #define INT_AGGR_DEF_TO 0x02
90 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
94 _ret = ufshcd_enable_vreg(_dev, _vreg); \
96 _ret = ufshcd_disable_vreg(_dev, _vreg); \
100 static u32 ufs_query_desc_max_size[] = {
101 QUERY_DESC_DEVICE_MAX_SIZE,
102 QUERY_DESC_CONFIGURAION_MAX_SIZE,
103 QUERY_DESC_UNIT_MAX_SIZE,
104 QUERY_DESC_RFU_MAX_SIZE,
105 QUERY_DESC_INTERCONNECT_MAX_SIZE,
106 QUERY_DESC_STRING_MAX_SIZE,
107 QUERY_DESC_RFU_MAX_SIZE,
108 QUERY_DESC_GEOMETRY_MAX_SIZE,
109 QUERY_DESC_POWER_MAX_SIZE,
110 QUERY_DESC_RFU_MAX_SIZE,
114 UFSHCD_MAX_CHANNEL = 0,
116 UFSHCD_CMD_PER_LUN = 32,
117 UFSHCD_CAN_QUEUE = 32,
124 UFSHCD_STATE_OPERATIONAL,
127 /* UFSHCD error handling flags */
129 UFSHCD_EH_IN_PROGRESS = (1 << 0),
132 /* UFSHCD UIC layer error flags */
134 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
135 UFSHCD_UIC_NL_ERROR = (1 << 1), /* Network layer error */
136 UFSHCD_UIC_TL_ERROR = (1 << 2), /* Transport Layer error */
137 UFSHCD_UIC_DME_ERROR = (1 << 3), /* DME error */
140 /* Interrupt configuration options */
147 #define ufshcd_set_eh_in_progress(h) \
148 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
149 #define ufshcd_eh_in_progress(h) \
150 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
151 #define ufshcd_clear_eh_in_progress(h) \
152 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_set_ufs_dev_active(h) \
155 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
156 #define ufshcd_set_ufs_dev_sleep(h) \
157 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
158 #define ufshcd_set_ufs_dev_poweroff(h) \
159 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
160 #define ufshcd_is_ufs_dev_active(h) \
161 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
162 #define ufshcd_is_ufs_dev_sleep(h) \
163 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
164 #define ufshcd_is_ufs_dev_poweroff(h) \
165 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
167 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
168 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
169 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
170 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
171 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
172 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
173 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
176 static inline enum ufs_dev_pwr_mode
177 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
179 return ufs_pm_lvl_states[lvl].dev_state;
182 static inline enum uic_link_state
183 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
185 return ufs_pm_lvl_states[lvl].link_state;
188 static void ufshcd_tmc_handler(struct ufs_hba *hba);
189 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
190 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
191 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
192 static void ufshcd_hba_exit(struct ufs_hba *hba);
193 static int ufshcd_probe_hba(struct ufs_hba *hba);
194 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
196 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
197 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
198 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
199 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
200 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
201 static irqreturn_t ufshcd_intr(int irq, void *__hba);
202 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
203 struct ufs_pa_layer_attr *desired_pwr_mode);
204 static int ufshcd_change_power_mode(struct ufs_hba *hba,
205 struct ufs_pa_layer_attr *pwr_mode);
206 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
208 return tag >= 0 && tag < hba->nutrs;
211 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
215 if (!hba->is_irq_enabled) {
216 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
219 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
221 hba->is_irq_enabled = true;
227 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
229 if (hba->is_irq_enabled) {
230 free_irq(hba->irq, hba);
231 hba->is_irq_enabled = false;
236 * ufshcd_wait_for_register - wait for register value to change
237 * @hba - per-adapter interface
238 * @reg - mmio register offset
239 * @mask - mask to apply to read register value
240 * @val - wait condition
241 * @interval_us - polling interval in microsecs
242 * @timeout_ms - timeout in millisecs
243 * @can_sleep - perform sleep or just spin
245 * Returns -ETIMEDOUT on error, zero on success
247 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
248 u32 val, unsigned long interval_us,
249 unsigned long timeout_ms, bool can_sleep)
252 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
254 /* ignore bits that we don't intend to wait on */
257 while ((ufshcd_readl(hba, reg) & mask) != val) {
259 usleep_range(interval_us, interval_us + 50);
262 if (time_after(jiffies, timeout)) {
263 if ((ufshcd_readl(hba, reg) & mask) != val)
273 * ufshcd_get_intr_mask - Get the interrupt bit mask
274 * @hba - Pointer to adapter instance
276 * Returns interrupt bit mask per version
278 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
280 if (hba->ufs_version == UFSHCI_VERSION_10)
281 return INTERRUPT_MASK_ALL_VER_10;
283 return INTERRUPT_MASK_ALL_VER_11;
287 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
288 * @hba - Pointer to adapter instance
290 * Returns UFSHCI version supported by the controller
292 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
294 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
295 return ufshcd_vops_get_ufs_hci_version(hba);
297 return ufshcd_readl(hba, REG_UFS_VERSION);
301 * ufshcd_is_device_present - Check if any device connected to
302 * the host controller
303 * @hba: pointer to adapter instance
305 * Returns 1 if device present, 0 if no device detected
307 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
309 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
310 DEVICE_PRESENT) ? 1 : 0;
314 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
315 * @lrb: pointer to local command reference block
317 * This function is used to get the OCS field from UTRD
318 * Returns the OCS field in the UTRD
320 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
322 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
326 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
327 * @task_req_descp: pointer to utp_task_req_desc structure
329 * This function is used to get the OCS field from UTMRD
330 * Returns the OCS field in the UTMRD
333 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
335 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
339 * ufshcd_get_tm_free_slot - get a free slot for task management request
340 * @hba: per adapter instance
341 * @free_slot: pointer to variable with available slot value
343 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
344 * Returns 0 if free slot is not available, else return 1 with tag value
347 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
356 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
357 if (tag >= hba->nutmrs)
359 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
367 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
369 clear_bit_unlock(slot, &hba->tm_slots_in_use);
373 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
374 * @hba: per adapter instance
375 * @pos: position of the bit to be cleared
377 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
379 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
383 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
384 * @hba: per adapter instance
385 * @tag: position of the bit to be cleared
387 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
389 __clear_bit(tag, &hba->outstanding_reqs);
393 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
394 * @reg: Register value of host controller status
396 * Returns integer, 0 on Success and positive value if failed
398 static inline int ufshcd_get_lists_status(u32 reg)
401 * The mask 0xFF is for the following HCS register bits
409 return ((reg & 0xFF) >> 1) ^ 0x07;
413 * ufshcd_get_uic_cmd_result - Get the UIC command result
414 * @hba: Pointer to adapter instance
416 * This function gets the result of UIC command completion
417 * Returns 0 on success, non zero value on error
419 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
421 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
422 MASK_UIC_COMMAND_RESULT;
426 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
427 * @hba: Pointer to adapter instance
429 * This function gets UIC command argument3
430 * Returns 0 on success, non zero value on error
432 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
434 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
438 * ufshcd_get_req_rsp - returns the TR response transaction type
439 * @ucd_rsp_ptr: pointer to response UPIU
442 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
444 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
448 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
449 * @ucd_rsp_ptr: pointer to response UPIU
451 * This function gets the response status and scsi_status from response UPIU
452 * Returns the response result code.
455 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
457 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
461 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
463 * @ucd_rsp_ptr: pointer to response UPIU
465 * Return the data segment length.
467 static inline unsigned int
468 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
470 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
471 MASK_RSP_UPIU_DATA_SEG_LEN;
475 * ufshcd_is_exception_event - Check if the device raised an exception event
476 * @ucd_rsp_ptr: pointer to response UPIU
478 * The function checks if the device raised an exception event indicated in
479 * the Device Information field of response UPIU.
481 * Returns true if exception is raised, false otherwise.
483 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
485 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
486 MASK_RSP_EXCEPTION_EVENT ? true : false;
490 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
491 * @hba: per adapter instance
494 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
496 ufshcd_writel(hba, INT_AGGR_ENABLE |
497 INT_AGGR_COUNTER_AND_TIMER_RESET,
498 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
502 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
503 * @hba: per adapter instance
504 * @cnt: Interrupt aggregation counter threshold
505 * @tmout: Interrupt aggregation timeout value
508 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
510 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
511 INT_AGGR_COUNTER_THLD_VAL(cnt) |
512 INT_AGGR_TIMEOUT_VAL(tmout),
513 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
517 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
518 * @hba: per adapter instance
520 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
522 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
526 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
527 * When run-stop registers are set to 1, it indicates the
528 * host controller that it can process the requests
529 * @hba: per adapter instance
531 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
533 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
534 REG_UTP_TASK_REQ_LIST_RUN_STOP);
535 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
536 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
540 * ufshcd_hba_start - Start controller initialization sequence
541 * @hba: per adapter instance
543 static inline void ufshcd_hba_start(struct ufs_hba *hba)
545 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
549 * ufshcd_is_hba_active - Get controller state
550 * @hba: per adapter instance
552 * Returns zero if controller is active, 1 otherwise
554 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
556 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
559 static void ufshcd_ungate_work(struct work_struct *work)
563 struct ufs_hba *hba = container_of(work, struct ufs_hba,
564 clk_gating.ungate_work);
566 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
568 spin_lock_irqsave(hba->host->host_lock, flags);
569 if (hba->clk_gating.state == CLKS_ON) {
570 spin_unlock_irqrestore(hba->host->host_lock, flags);
574 spin_unlock_irqrestore(hba->host->host_lock, flags);
575 ufshcd_setup_clocks(hba, true);
577 /* Exit from hibern8 */
578 if (ufshcd_can_hibern8_during_gating(hba)) {
579 /* Prevent gating in this path */
580 hba->clk_gating.is_suspended = true;
581 if (ufshcd_is_link_hibern8(hba)) {
582 ret = ufshcd_uic_hibern8_exit(hba);
584 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
587 ufshcd_set_link_active(hba);
589 hba->clk_gating.is_suspended = false;
592 if (ufshcd_is_clkscaling_enabled(hba))
593 devfreq_resume_device(hba->devfreq);
594 scsi_unblock_requests(hba->host);
598 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
599 * Also, exit from hibern8 mode and set the link as active.
600 * @hba: per adapter instance
601 * @async: This indicates whether caller should ungate clocks asynchronously.
603 int ufshcd_hold(struct ufs_hba *hba, bool async)
608 if (!ufshcd_is_clkgating_allowed(hba))
610 spin_lock_irqsave(hba->host->host_lock, flags);
611 hba->clk_gating.active_reqs++;
613 if (ufshcd_eh_in_progress(hba)) {
614 spin_unlock_irqrestore(hba->host->host_lock, flags);
619 switch (hba->clk_gating.state) {
623 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
624 hba->clk_gating.state = CLKS_ON;
628 * If we here, it means gating work is either done or
629 * currently running. Hence, fall through to cancel gating
630 * work and to enable clocks.
633 scsi_block_requests(hba->host);
634 hba->clk_gating.state = REQ_CLKS_ON;
635 schedule_work(&hba->clk_gating.ungate_work);
637 * fall through to check if we should wait for this
638 * work to be done or not.
643 hba->clk_gating.active_reqs--;
647 spin_unlock_irqrestore(hba->host->host_lock, flags);
648 flush_work(&hba->clk_gating.ungate_work);
649 /* Make sure state is CLKS_ON before returning */
650 spin_lock_irqsave(hba->host->host_lock, flags);
653 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
654 __func__, hba->clk_gating.state);
657 spin_unlock_irqrestore(hba->host->host_lock, flags);
661 EXPORT_SYMBOL_GPL(ufshcd_hold);
663 static void ufshcd_gate_work(struct work_struct *work)
665 struct ufs_hba *hba = container_of(work, struct ufs_hba,
666 clk_gating.gate_work.work);
669 spin_lock_irqsave(hba->host->host_lock, flags);
670 if (hba->clk_gating.is_suspended) {
671 hba->clk_gating.state = CLKS_ON;
675 if (hba->clk_gating.active_reqs
676 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
677 || hba->lrb_in_use || hba->outstanding_tasks
678 || hba->active_uic_cmd || hba->uic_async_done)
681 spin_unlock_irqrestore(hba->host->host_lock, flags);
683 /* put the link into hibern8 mode before turning off clocks */
684 if (ufshcd_can_hibern8_during_gating(hba)) {
685 if (ufshcd_uic_hibern8_enter(hba)) {
686 hba->clk_gating.state = CLKS_ON;
689 ufshcd_set_link_hibern8(hba);
692 if (ufshcd_is_clkscaling_enabled(hba)) {
693 devfreq_suspend_device(hba->devfreq);
694 hba->clk_scaling.window_start_t = 0;
697 if (!ufshcd_is_link_active(hba))
698 ufshcd_setup_clocks(hba, false);
700 /* If link is active, device ref_clk can't be switched off */
701 __ufshcd_setup_clocks(hba, false, true);
704 * In case you are here to cancel this work the gating state
705 * would be marked as REQ_CLKS_ON. In this case keep the state
706 * as REQ_CLKS_ON which would anyway imply that clocks are off
707 * and a request to turn them on is pending. By doing this way,
708 * we keep the state machine in tact and this would ultimately
709 * prevent from doing cancel work multiple times when there are
710 * new requests arriving before the current cancel work is done.
712 spin_lock_irqsave(hba->host->host_lock, flags);
713 if (hba->clk_gating.state == REQ_CLKS_OFF)
714 hba->clk_gating.state = CLKS_OFF;
717 spin_unlock_irqrestore(hba->host->host_lock, flags);
722 /* host lock must be held before calling this variant */
723 static void __ufshcd_release(struct ufs_hba *hba)
725 if (!ufshcd_is_clkgating_allowed(hba))
728 hba->clk_gating.active_reqs--;
730 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
731 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
732 || hba->lrb_in_use || hba->outstanding_tasks
733 || hba->active_uic_cmd || hba->uic_async_done
734 || ufshcd_eh_in_progress(hba))
737 hba->clk_gating.state = REQ_CLKS_OFF;
738 schedule_delayed_work(&hba->clk_gating.gate_work,
739 msecs_to_jiffies(hba->clk_gating.delay_ms));
742 void ufshcd_release(struct ufs_hba *hba)
746 spin_lock_irqsave(hba->host->host_lock, flags);
747 __ufshcd_release(hba);
748 spin_unlock_irqrestore(hba->host->host_lock, flags);
750 EXPORT_SYMBOL_GPL(ufshcd_release);
752 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
753 struct device_attribute *attr, char *buf)
755 struct ufs_hba *hba = dev_get_drvdata(dev);
757 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
760 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
761 struct device_attribute *attr, const char *buf, size_t count)
763 struct ufs_hba *hba = dev_get_drvdata(dev);
764 unsigned long flags, value;
766 if (kstrtoul(buf, 0, &value))
769 spin_lock_irqsave(hba->host->host_lock, flags);
770 hba->clk_gating.delay_ms = value;
771 spin_unlock_irqrestore(hba->host->host_lock, flags);
775 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
777 if (!ufshcd_is_clkgating_allowed(hba))
780 hba->clk_gating.delay_ms = 150;
781 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
782 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
784 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
785 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
786 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
787 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
788 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
789 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
790 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
793 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
795 if (!ufshcd_is_clkgating_allowed(hba))
797 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
798 cancel_work_sync(&hba->clk_gating.ungate_work);
799 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
802 /* Must be called with host lock acquired */
803 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
805 if (!ufshcd_is_clkscaling_enabled(hba))
808 if (!hba->clk_scaling.is_busy_started) {
809 hba->clk_scaling.busy_start_t = ktime_get();
810 hba->clk_scaling.is_busy_started = true;
814 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
816 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
818 if (!ufshcd_is_clkscaling_enabled(hba))
821 if (!hba->outstanding_reqs && scaling->is_busy_started) {
822 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
823 scaling->busy_start_t));
824 scaling->busy_start_t = ktime_set(0, 0);
825 scaling->is_busy_started = false;
829 * ufshcd_send_command - Send SCSI or device management commands
830 * @hba: per adapter instance
831 * @task_tag: Task tag of the command
834 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
836 ufshcd_clk_scaling_start_busy(hba);
837 __set_bit(task_tag, &hba->outstanding_reqs);
838 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
842 * ufshcd_copy_sense_data - Copy sense data in case of check condition
843 * @lrb - pointer to local reference block
845 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
848 if (lrbp->sense_buffer &&
849 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
850 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
851 memcpy(lrbp->sense_buffer,
852 lrbp->ucd_rsp_ptr->sr.sense_data,
853 min_t(int, len, SCSI_SENSE_BUFFERSIZE));
858 * ufshcd_copy_query_response() - Copy the Query Response and the data
860 * @hba: per adapter instance
861 * @lrb - pointer to local reference block
864 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
866 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
868 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
870 /* Get the descriptor */
871 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
872 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
873 GENERAL_UPIU_REQUEST_SIZE;
877 /* data segment length */
878 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
879 MASK_QUERY_DATA_SEG_LEN;
880 buf_len = be16_to_cpu(
881 hba->dev_cmd.query.request.upiu_req.length);
882 if (likely(buf_len >= resp_len)) {
883 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
886 "%s: Response size is bigger than buffer",
896 * ufshcd_hba_capabilities - Read controller capabilities
897 * @hba: per adapter instance
899 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
901 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
903 /* nutrs and nutmrs are 0 based values */
904 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
906 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
910 * ufshcd_ready_for_uic_cmd - Check if controller is ready
911 * to accept UIC commands
912 * @hba: per adapter instance
913 * Return true on success, else false
915 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
917 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
924 * ufshcd_get_upmcrs - Get the power mode change request status
925 * @hba: Pointer to adapter instance
927 * This function gets the UPMCRS field of HCS register
928 * Returns value of UPMCRS field
930 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
932 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
936 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
937 * @hba: per adapter instance
938 * @uic_cmd: UIC command
940 * Mutex must be held.
943 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
945 WARN_ON(hba->active_uic_cmd);
947 hba->active_uic_cmd = uic_cmd;
950 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
951 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
952 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
955 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
960 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
961 * @hba: per adapter instance
962 * @uic_command: UIC command
964 * Must be called with mutex held.
965 * Returns 0 only if success.
968 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
973 if (wait_for_completion_timeout(&uic_cmd->done,
974 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
975 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
979 spin_lock_irqsave(hba->host->host_lock, flags);
980 hba->active_uic_cmd = NULL;
981 spin_unlock_irqrestore(hba->host->host_lock, flags);
987 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
988 * @hba: per adapter instance
989 * @uic_cmd: UIC command
990 * @completion: initialize the completion only if this is set to true
992 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
993 * with mutex held and host_lock locked.
994 * Returns 0 only if success.
997 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1000 if (!ufshcd_ready_for_uic_cmd(hba)) {
1002 "Controller not ready to accept UIC commands\n");
1007 init_completion(&uic_cmd->done);
1009 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1015 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1016 * @hba: per adapter instance
1017 * @uic_cmd: UIC command
1019 * Returns 0 only if success.
1022 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1025 unsigned long flags;
1027 ufshcd_hold(hba, false);
1028 mutex_lock(&hba->uic_cmd_mutex);
1029 ufshcd_add_delay_before_dme_cmd(hba);
1031 spin_lock_irqsave(hba->host->host_lock, flags);
1032 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1033 spin_unlock_irqrestore(hba->host->host_lock, flags);
1035 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1037 mutex_unlock(&hba->uic_cmd_mutex);
1039 ufshcd_release(hba);
1044 * ufshcd_map_sg - Map scatter-gather list to prdt
1045 * @lrbp - pointer to local reference block
1047 * Returns 0 in case of success, non-zero value in case of failure
1049 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1051 struct ufshcd_sg_entry *prd_table;
1052 struct scatterlist *sg;
1053 struct scsi_cmnd *cmd;
1058 sg_segments = scsi_dma_map(cmd);
1059 if (sg_segments < 0)
1063 lrbp->utr_descriptor_ptr->prd_table_length =
1064 cpu_to_le16((u16) (sg_segments));
1066 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1068 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1070 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1071 prd_table[i].base_addr =
1072 cpu_to_le32(lower_32_bits(sg->dma_address));
1073 prd_table[i].upper_addr =
1074 cpu_to_le32(upper_32_bits(sg->dma_address));
1075 prd_table[i].reserved = 0;
1078 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1085 * ufshcd_enable_intr - enable interrupts
1086 * @hba: per adapter instance
1087 * @intrs: interrupt bits
1089 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1091 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1093 if (hba->ufs_version == UFSHCI_VERSION_10) {
1095 rw = set & INTERRUPT_MASK_RW_VER_10;
1096 set = rw | ((set ^ intrs) & intrs);
1101 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1105 * ufshcd_disable_intr - disable interrupts
1106 * @hba: per adapter instance
1107 * @intrs: interrupt bits
1109 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1111 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1113 if (hba->ufs_version == UFSHCI_VERSION_10) {
1115 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1116 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1117 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1123 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1127 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1128 * descriptor according to request
1129 * @lrbp: pointer to local reference block
1130 * @upiu_flags: flags required in the header
1131 * @cmd_dir: requests data direction
1133 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1134 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1136 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1140 if (cmd_dir == DMA_FROM_DEVICE) {
1141 data_direction = UTP_DEVICE_TO_HOST;
1142 *upiu_flags = UPIU_CMD_FLAGS_READ;
1143 } else if (cmd_dir == DMA_TO_DEVICE) {
1144 data_direction = UTP_HOST_TO_DEVICE;
1145 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1147 data_direction = UTP_NO_DATA_TRANSFER;
1148 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1151 dword_0 = data_direction | (lrbp->command_type
1152 << UPIU_COMMAND_TYPE_OFFSET);
1154 dword_0 |= UTP_REQ_DESC_INT_CMD;
1156 /* Transfer request descriptor header fields */
1157 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1158 /* dword_1 is reserved, hence it is set to 0 */
1159 req_desc->header.dword_1 = 0;
1161 * assigning invalid value for command status. Controller
1162 * updates OCS on command completion, with the command
1165 req_desc->header.dword_2 =
1166 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1167 /* dword_3 is reserved, hence it is set to 0 */
1168 req_desc->header.dword_3 = 0;
1170 req_desc->prd_table_length = 0;
1174 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1176 * @lrbp - local reference block pointer
1177 * @upiu_flags - flags
1180 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1182 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1183 unsigned short cdb_len;
1185 /* command descriptor fields */
1186 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1187 UPIU_TRANSACTION_COMMAND, upiu_flags,
1188 lrbp->lun, lrbp->task_tag);
1189 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1190 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1192 /* Total EHS length and Data segment length will be zero */
1193 ucd_req_ptr->header.dword_2 = 0;
1195 ucd_req_ptr->sc.exp_data_transfer_len =
1196 cpu_to_be32(lrbp->cmd->sdb.length);
1198 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1199 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1200 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1202 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1206 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1209 * @lrbp: local reference block pointer
1210 * @upiu_flags: flags
1212 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1213 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1215 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1216 struct ufs_query *query = &hba->dev_cmd.query;
1217 u16 len = be16_to_cpu(query->request.upiu_req.length);
1218 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1220 /* Query request header */
1221 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1222 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1223 lrbp->lun, lrbp->task_tag);
1224 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1225 0, query->request.query_func, 0, 0);
1227 /* Data segment length */
1228 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1229 0, 0, len >> 8, (u8)len);
1231 /* Copy the Query Request buffer as is */
1232 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1235 /* Copy the Descriptor */
1236 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1237 memcpy(descp, query->descriptor, len);
1239 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1242 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1244 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1246 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1248 /* command descriptor fields */
1249 ucd_req_ptr->header.dword_0 =
1251 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1252 /* clear rest of the fields of basic header */
1253 ucd_req_ptr->header.dword_1 = 0;
1254 ucd_req_ptr->header.dword_2 = 0;
1256 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1260 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
1261 * @hba - per adapter instance
1262 * @lrb - pointer to local reference block
1264 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1269 switch (lrbp->command_type) {
1270 case UTP_CMD_TYPE_SCSI:
1271 if (likely(lrbp->cmd)) {
1272 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1273 lrbp->cmd->sc_data_direction);
1274 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1279 case UTP_CMD_TYPE_DEV_MANAGE:
1280 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1281 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1282 ufshcd_prepare_utp_query_req_upiu(
1283 hba, lrbp, upiu_flags);
1284 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1285 ufshcd_prepare_utp_nop_upiu(lrbp);
1289 case UTP_CMD_TYPE_UFS:
1290 /* For UFS native command implementation */
1292 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1297 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1298 __func__, lrbp->command_type);
1300 } /* end of switch */
1306 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1307 * @scsi_lun: scsi LUN id
1309 * Returns UPIU LUN id
1311 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1313 if (scsi_is_wlun(scsi_lun))
1314 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1317 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1321 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1322 * @scsi_lun: UPIU W-LUN id
1324 * Returns SCSI W-LUN id
1326 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1328 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1332 * ufshcd_queuecommand - main entry point for SCSI requests
1333 * @cmd: command from SCSI Midlayer
1334 * @done: call back function
1336 * Returns 0 for success, non-zero in case of failure
1338 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1340 struct ufshcd_lrb *lrbp;
1341 struct ufs_hba *hba;
1342 unsigned long flags;
1346 hba = shost_priv(host);
1348 tag = cmd->request->tag;
1349 if (!ufshcd_valid_tag(hba, tag)) {
1351 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1352 __func__, tag, cmd, cmd->request);
1356 spin_lock_irqsave(hba->host->host_lock, flags);
1357 switch (hba->ufshcd_state) {
1358 case UFSHCD_STATE_OPERATIONAL:
1360 case UFSHCD_STATE_RESET:
1361 err = SCSI_MLQUEUE_HOST_BUSY;
1363 case UFSHCD_STATE_ERROR:
1364 set_host_byte(cmd, DID_ERROR);
1365 cmd->scsi_done(cmd);
1368 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1369 __func__, hba->ufshcd_state);
1370 set_host_byte(cmd, DID_BAD_TARGET);
1371 cmd->scsi_done(cmd);
1375 /* if error handling is in progress, don't issue commands */
1376 if (ufshcd_eh_in_progress(hba)) {
1377 set_host_byte(cmd, DID_ERROR);
1378 cmd->scsi_done(cmd);
1381 spin_unlock_irqrestore(hba->host->host_lock, flags);
1383 /* acquire the tag to make sure device cmds don't use it */
1384 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1386 * Dev manage command in progress, requeue the command.
1387 * Requeuing the command helps in cases where the request *may*
1388 * find different tag instead of waiting for dev manage command
1391 err = SCSI_MLQUEUE_HOST_BUSY;
1395 err = ufshcd_hold(hba, true);
1397 err = SCSI_MLQUEUE_HOST_BUSY;
1398 clear_bit_unlock(tag, &hba->lrb_in_use);
1401 WARN_ON(hba->clk_gating.state != CLKS_ON);
1403 lrbp = &hba->lrb[tag];
1407 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1408 lrbp->sense_buffer = cmd->sense_buffer;
1409 lrbp->task_tag = tag;
1410 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1411 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1412 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1414 /* form UPIU before issuing the command */
1415 ufshcd_compose_upiu(hba, lrbp);
1416 err = ufshcd_map_sg(lrbp);
1419 clear_bit_unlock(tag, &hba->lrb_in_use);
1423 /* issue command to the controller */
1424 spin_lock_irqsave(hba->host->host_lock, flags);
1425 ufshcd_send_command(hba, tag);
1427 spin_unlock_irqrestore(hba->host->host_lock, flags);
1432 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1433 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1436 lrbp->sense_bufflen = 0;
1437 lrbp->sense_buffer = NULL;
1438 lrbp->task_tag = tag;
1439 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1440 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1441 lrbp->intr_cmd = true; /* No interrupt aggregation */
1442 hba->dev_cmd.type = cmd_type;
1444 return ufshcd_compose_upiu(hba, lrbp);
1448 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1451 unsigned long flags;
1452 u32 mask = 1 << tag;
1454 /* clear outstanding transaction before retry */
1455 spin_lock_irqsave(hba->host->host_lock, flags);
1456 ufshcd_utrl_clear(hba, tag);
1457 spin_unlock_irqrestore(hba->host->host_lock, flags);
1460 * wait for for h/w to clear corresponding bit in door-bell.
1461 * max. wait is 1 sec.
1463 err = ufshcd_wait_for_register(hba,
1464 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1465 mask, ~mask, 1000, 1000, true);
1471 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1473 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1475 /* Get the UPIU response */
1476 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1477 UPIU_RSP_CODE_OFFSET;
1478 return query_res->response;
1482 * ufshcd_dev_cmd_completion() - handles device management command responses
1483 * @hba: per adapter instance
1484 * @lrbp: pointer to local reference block
1487 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1492 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1495 case UPIU_TRANSACTION_NOP_IN:
1496 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1498 dev_err(hba->dev, "%s: unexpected response %x\n",
1502 case UPIU_TRANSACTION_QUERY_RSP:
1503 err = ufshcd_check_query_response(hba, lrbp);
1505 err = ufshcd_copy_query_response(hba, lrbp);
1507 case UPIU_TRANSACTION_REJECT_UPIU:
1508 /* TODO: handle Reject UPIU Response */
1510 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1515 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1523 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1524 struct ufshcd_lrb *lrbp, int max_timeout)
1527 unsigned long time_left;
1528 unsigned long flags;
1530 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1531 msecs_to_jiffies(max_timeout));
1533 spin_lock_irqsave(hba->host->host_lock, flags);
1534 hba->dev_cmd.complete = NULL;
1535 if (likely(time_left)) {
1536 err = ufshcd_get_tr_ocs(lrbp);
1538 err = ufshcd_dev_cmd_completion(hba, lrbp);
1540 spin_unlock_irqrestore(hba->host->host_lock, flags);
1544 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1545 __func__, lrbp->task_tag);
1546 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1547 /* successfully cleared the command, retry if needed */
1550 * in case of an error, after clearing the doorbell,
1551 * we also need to clear the outstanding_request
1554 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
1561 * ufshcd_get_dev_cmd_tag - Get device management command tag
1562 * @hba: per-adapter instance
1563 * @tag: pointer to variable with available slot value
1565 * Get a free slot and lock it until device management command
1568 * Returns false if free slot is unavailable for locking, else
1569 * return true with tag value in @tag.
1571 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1581 tmp = ~hba->lrb_in_use;
1582 tag = find_last_bit(&tmp, hba->nutrs);
1583 if (tag >= hba->nutrs)
1585 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1593 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1595 clear_bit_unlock(tag, &hba->lrb_in_use);
1599 * ufshcd_exec_dev_cmd - API for sending device management requests
1601 * @cmd_type - specifies the type (NOP, Query...)
1602 * @timeout - time in seconds
1604 * NOTE: Since there is only one available tag for device management commands,
1605 * it is expected you hold the hba->dev_cmd.lock mutex.
1607 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1608 enum dev_cmd_type cmd_type, int timeout)
1610 struct ufshcd_lrb *lrbp;
1613 struct completion wait;
1614 unsigned long flags;
1617 * Get free slot, sleep if slots are unavailable.
1618 * Even though we use wait_event() which sleeps indefinitely,
1619 * the maximum wait time is bounded by SCSI request timeout.
1621 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1623 init_completion(&wait);
1624 lrbp = &hba->lrb[tag];
1626 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1630 hba->dev_cmd.complete = &wait;
1632 /* Make sure descriptors are ready before ringing the doorbell */
1634 spin_lock_irqsave(hba->host->host_lock, flags);
1635 ufshcd_send_command(hba, tag);
1636 spin_unlock_irqrestore(hba->host->host_lock, flags);
1638 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1641 ufshcd_put_dev_cmd_tag(hba, tag);
1642 wake_up(&hba->dev_cmd.tag_wq);
1647 * ufshcd_init_query() - init the query response and request parameters
1648 * @hba: per-adapter instance
1649 * @request: address of the request pointer to be initialized
1650 * @response: address of the response pointer to be initialized
1651 * @opcode: operation to perform
1652 * @idn: flag idn to access
1653 * @index: LU number to access
1654 * @selector: query/flag/descriptor further identification
1656 static inline void ufshcd_init_query(struct ufs_hba *hba,
1657 struct ufs_query_req **request, struct ufs_query_res **response,
1658 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1660 *request = &hba->dev_cmd.query.request;
1661 *response = &hba->dev_cmd.query.response;
1662 memset(*request, 0, sizeof(struct ufs_query_req));
1663 memset(*response, 0, sizeof(struct ufs_query_res));
1664 (*request)->upiu_req.opcode = opcode;
1665 (*request)->upiu_req.idn = idn;
1666 (*request)->upiu_req.index = index;
1667 (*request)->upiu_req.selector = selector;
1670 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1671 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1676 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1677 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1680 "%s: failed with error %d, retries %d\n",
1681 __func__, ret, retries);
1688 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1689 __func__, opcode, idn, ret, retries);
1694 * ufshcd_query_flag() - API function for sending flag query requests
1695 * hba: per-adapter instance
1696 * query_opcode: flag query to perform
1697 * idn: flag idn to access
1698 * flag_res: the flag value after the query request completes
1700 * Returns 0 for success, non-zero in case of failure
1702 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1703 enum flag_idn idn, bool *flag_res)
1705 struct ufs_query_req *request = NULL;
1706 struct ufs_query_res *response = NULL;
1707 int err, index = 0, selector = 0;
1708 int timeout = QUERY_REQ_TIMEOUT;
1712 ufshcd_hold(hba, false);
1713 mutex_lock(&hba->dev_cmd.lock);
1714 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1718 case UPIU_QUERY_OPCODE_SET_FLAG:
1719 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1720 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1721 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1723 case UPIU_QUERY_OPCODE_READ_FLAG:
1724 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1726 /* No dummy reads */
1727 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1735 "%s: Expected query flag opcode but got = %d\n",
1741 if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1742 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1744 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
1748 "%s: Sending flag query for idn %d failed, err = %d\n",
1749 __func__, idn, err);
1754 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1755 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1758 mutex_unlock(&hba->dev_cmd.lock);
1759 ufshcd_release(hba);
1764 * ufshcd_query_attr - API function for sending attribute requests
1765 * hba: per-adapter instance
1766 * opcode: attribute opcode
1767 * idn: attribute idn to access
1768 * index: index field
1769 * selector: selector field
1770 * attr_val: the attribute value after the query request completes
1772 * Returns 0 for success, non-zero in case of failure
1774 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1775 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1777 struct ufs_query_req *request = NULL;
1778 struct ufs_query_res *response = NULL;
1783 ufshcd_hold(hba, false);
1785 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1791 mutex_lock(&hba->dev_cmd.lock);
1792 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1796 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1797 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1798 request->upiu_req.value = cpu_to_be32(*attr_val);
1800 case UPIU_QUERY_OPCODE_READ_ATTR:
1801 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1804 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1810 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1813 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1814 __func__, opcode, idn, err);
1818 *attr_val = be32_to_cpu(response->upiu_res.value);
1821 mutex_unlock(&hba->dev_cmd.lock);
1823 ufshcd_release(hba);
1828 * ufshcd_query_attr_retry() - API function for sending query
1829 * attribute with retries
1830 * @hba: per-adapter instance
1831 * @opcode: attribute opcode
1832 * @idn: attribute idn to access
1833 * @index: index field
1834 * @selector: selector field
1835 * @attr_val: the attribute value after the query request
1838 * Returns 0 for success, non-zero in case of failure
1840 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1841 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1847 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1848 ret = ufshcd_query_attr(hba, opcode, idn, index,
1849 selector, attr_val);
1851 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1852 __func__, ret, retries);
1859 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1860 __func__, idn, ret, QUERY_REQ_RETRIES);
1865 * ufshcd_query_descriptor - API function for sending descriptor requests
1866 * hba: per-adapter instance
1867 * opcode: attribute opcode
1868 * idn: attribute idn to access
1869 * index: index field
1870 * selector: selector field
1871 * desc_buf: the buffer that contains the descriptor
1872 * buf_len: length parameter passed to the device
1874 * Returns 0 for success, non-zero in case of failure.
1875 * The buf_len parameter will contain, on return, the length parameter
1876 * received on the response.
1878 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1879 enum query_opcode opcode, enum desc_idn idn, u8 index,
1880 u8 selector, u8 *desc_buf, int *buf_len)
1882 struct ufs_query_req *request = NULL;
1883 struct ufs_query_res *response = NULL;
1888 ufshcd_hold(hba, false);
1890 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1896 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1897 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1898 __func__, *buf_len);
1903 mutex_lock(&hba->dev_cmd.lock);
1904 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1906 hba->dev_cmd.query.descriptor = desc_buf;
1907 request->upiu_req.length = cpu_to_be16(*buf_len);
1910 case UPIU_QUERY_OPCODE_WRITE_DESC:
1911 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1913 case UPIU_QUERY_OPCODE_READ_DESC:
1914 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1918 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1924 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1927 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1928 __func__, opcode, idn, err);
1932 hba->dev_cmd.query.descriptor = NULL;
1933 *buf_len = be16_to_cpu(response->upiu_res.length);
1936 mutex_unlock(&hba->dev_cmd.lock);
1938 ufshcd_release(hba);
1943 * ufshcd_read_desc_param - read the specified descriptor parameter
1944 * @hba: Pointer to adapter instance
1945 * @desc_id: descriptor idn value
1946 * @desc_index: descriptor index
1947 * @param_offset: offset of the parameter to read
1948 * @param_read_buf: pointer to buffer where parameter would be read
1949 * @param_size: sizeof(param_read_buf)
1951 * Return 0 in case of success, non-zero otherwise
1953 static int ufshcd_read_desc_param(struct ufs_hba *hba,
1954 enum desc_idn desc_id,
1963 bool is_kmalloc = true;
1966 if (desc_id >= QUERY_DESC_IDN_MAX)
1969 buff_len = ufs_query_desc_max_size[desc_id];
1970 if ((param_offset + param_size) > buff_len)
1973 if (!param_offset && (param_size == buff_len)) {
1974 /* memory space already available to hold full descriptor */
1975 desc_buf = param_read_buf;
1978 /* allocate memory to hold full descriptor */
1979 desc_buf = kmalloc(buff_len, GFP_KERNEL);
1984 ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
1985 desc_id, desc_index, 0, desc_buf,
1988 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
1989 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
1990 ufs_query_desc_max_size[desc_id])
1991 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
1992 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
1993 __func__, desc_id, param_offset, buff_len, ret);
2001 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2008 static inline int ufshcd_read_desc(struct ufs_hba *hba,
2009 enum desc_idn desc_id,
2014 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2017 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2021 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2025 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2026 * @hba: Pointer to adapter instance
2028 * @param_offset: offset of the parameter to read
2029 * @param_read_buf: pointer to buffer where parameter would be read
2030 * @param_size: sizeof(param_read_buf)
2032 * Return 0 in case of success, non-zero otherwise
2034 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2036 enum unit_desc_param param_offset,
2041 * Unit descriptors are only available for general purpose LUs (LUN id
2042 * from 0 to 7) and RPMB Well known LU.
2044 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
2047 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2048 param_offset, param_read_buf, param_size);
2052 * ufshcd_memory_alloc - allocate memory for host memory space data structures
2053 * @hba: per adapter instance
2055 * 1. Allocate DMA memory for Command Descriptor array
2056 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2057 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2058 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2060 * 4. Allocate memory for local reference block(lrb).
2062 * Returns 0 for success, non-zero in case of failure
2064 static int ufshcd_memory_alloc(struct ufs_hba *hba)
2066 size_t utmrdl_size, utrdl_size, ucdl_size;
2068 /* Allocate memory for UTP command descriptors */
2069 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2070 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2072 &hba->ucdl_dma_addr,
2076 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2077 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2078 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2079 * be aligned to 128 bytes as well
2081 if (!hba->ucdl_base_addr ||
2082 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
2084 "Command Descriptor Memory allocation failed\n");
2089 * Allocate memory for UTP Transfer descriptors
2090 * UFSHCI requires 1024 byte alignment of UTRD
2092 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2093 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2095 &hba->utrdl_dma_addr,
2097 if (!hba->utrdl_base_addr ||
2098 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
2100 "Transfer Descriptor Memory allocation failed\n");
2105 * Allocate memory for UTP Task Management descriptors
2106 * UFSHCI requires 1024 byte alignment of UTMRD
2108 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2109 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2111 &hba->utmrdl_dma_addr,
2113 if (!hba->utmrdl_base_addr ||
2114 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
2116 "Task Management Descriptor Memory allocation failed\n");
2120 /* Allocate memory for local reference block */
2121 hba->lrb = devm_kzalloc(hba->dev,
2122 hba->nutrs * sizeof(struct ufshcd_lrb),
2125 dev_err(hba->dev, "LRB Memory allocation failed\n");
2134 * ufshcd_host_memory_configure - configure local reference block with
2136 * @hba: per adapter instance
2138 * Configure Host memory space
2139 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2141 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2143 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2144 * into local reference block.
2146 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2148 struct utp_transfer_cmd_desc *cmd_descp;
2149 struct utp_transfer_req_desc *utrdlp;
2150 dma_addr_t cmd_desc_dma_addr;
2151 dma_addr_t cmd_desc_element_addr;
2152 u16 response_offset;
2157 utrdlp = hba->utrdl_base_addr;
2158 cmd_descp = hba->ucdl_base_addr;
2161 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2163 offsetof(struct utp_transfer_cmd_desc, prd_table);
2165 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2166 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2168 for (i = 0; i < hba->nutrs; i++) {
2169 /* Configure UTRD with command descriptor base address */
2170 cmd_desc_element_addr =
2171 (cmd_desc_dma_addr + (cmd_desc_size * i));
2172 utrdlp[i].command_desc_base_addr_lo =
2173 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2174 utrdlp[i].command_desc_base_addr_hi =
2175 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2177 /* Response upiu and prdt offset should be in double words */
2178 utrdlp[i].response_upiu_offset =
2179 cpu_to_le16((response_offset >> 2));
2180 utrdlp[i].prd_table_offset =
2181 cpu_to_le16((prdt_offset >> 2));
2182 utrdlp[i].response_upiu_length =
2183 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2185 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2186 hba->lrb[i].ucd_req_ptr =
2187 (struct utp_upiu_req *)(cmd_descp + i);
2188 hba->lrb[i].ucd_rsp_ptr =
2189 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2190 hba->lrb[i].ucd_prdt_ptr =
2191 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2196 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2197 * @hba: per adapter instance
2199 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2200 * in order to initialize the Unipro link startup procedure.
2201 * Once the Unipro links are up, the device connected to the controller
2204 * Returns 0 on success, non-zero value on failure
2206 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2208 struct uic_command uic_cmd = {0};
2211 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2213 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2216 "dme-link-startup: error code %d\n", ret);
2220 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2222 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2223 unsigned long min_sleep_time_us;
2225 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2229 * last_dme_cmd_tstamp will be 0 only for 1st call to
2232 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2233 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2235 unsigned long delta =
2236 (unsigned long) ktime_to_us(
2237 ktime_sub(ktime_get(),
2238 hba->last_dme_cmd_tstamp));
2240 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2242 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2244 return; /* no more delay required */
2247 /* allow sleep for extra 50us if needed */
2248 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2252 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2253 * @hba: per adapter instance
2254 * @attr_sel: uic command argument1
2255 * @attr_set: attribute set type as uic command argument2
2256 * @mib_val: setting value as uic command argument3
2257 * @peer: indicate whether peer or local
2259 * Returns 0 on success, non-zero value on failure
2261 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2262 u8 attr_set, u32 mib_val, u8 peer)
2264 struct uic_command uic_cmd = {0};
2265 static const char *const action[] = {
2269 const char *set = action[!!peer];
2271 int retries = UFS_UIC_COMMAND_RETRIES;
2273 uic_cmd.command = peer ?
2274 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2275 uic_cmd.argument1 = attr_sel;
2276 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2277 uic_cmd.argument3 = mib_val;
2280 /* for peer attributes we retry upon failure */
2281 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2283 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2284 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2285 } while (ret && peer && --retries);
2288 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2289 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2294 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2297 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2298 * @hba: per adapter instance
2299 * @attr_sel: uic command argument1
2300 * @mib_val: the value of the attribute as returned by the UIC command
2301 * @peer: indicate whether peer or local
2303 * Returns 0 on success, non-zero value on failure
2305 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2306 u32 *mib_val, u8 peer)
2308 struct uic_command uic_cmd = {0};
2309 static const char *const action[] = {
2313 const char *get = action[!!peer];
2315 int retries = UFS_UIC_COMMAND_RETRIES;
2316 struct ufs_pa_layer_attr orig_pwr_info;
2317 struct ufs_pa_layer_attr temp_pwr_info;
2318 bool pwr_mode_change = false;
2320 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2321 orig_pwr_info = hba->pwr_info;
2322 temp_pwr_info = orig_pwr_info;
2324 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2325 orig_pwr_info.pwr_rx == FAST_MODE) {
2326 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2327 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2328 pwr_mode_change = true;
2329 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2330 orig_pwr_info.pwr_rx == SLOW_MODE) {
2331 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2332 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2333 pwr_mode_change = true;
2335 if (pwr_mode_change) {
2336 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2342 uic_cmd.command = peer ?
2343 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2344 uic_cmd.argument1 = attr_sel;
2347 /* for peer attributes we retry upon failure */
2348 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2350 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2351 get, UIC_GET_ATTR_ID(attr_sel), ret);
2352 } while (ret && peer && --retries);
2355 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2356 get, UIC_GET_ATTR_ID(attr_sel), retries);
2358 if (mib_val && !ret)
2359 *mib_val = uic_cmd.argument3;
2361 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2363 ufshcd_change_power_mode(hba, &orig_pwr_info);
2367 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2370 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2371 * state) and waits for it to take effect.
2373 * @hba: per adapter instance
2374 * @cmd: UIC command to execute
2376 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2377 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2378 * and device UniPro link and hence it's final completion would be indicated by
2379 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2380 * addition to normal UIC command completion Status (UCCS). This function only
2381 * returns after the relevant status bits indicate the completion.
2383 * Returns 0 on success, non-zero value on failure
2385 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2387 struct completion uic_async_done;
2388 unsigned long flags;
2391 bool reenable_intr = false;
2393 mutex_lock(&hba->uic_cmd_mutex);
2394 init_completion(&uic_async_done);
2395 ufshcd_add_delay_before_dme_cmd(hba);
2397 spin_lock_irqsave(hba->host->host_lock, flags);
2398 hba->uic_async_done = &uic_async_done;
2399 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2400 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2402 * Make sure UIC command completion interrupt is disabled before
2403 * issuing UIC command.
2406 reenable_intr = true;
2408 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2409 spin_unlock_irqrestore(hba->host->host_lock, flags);
2412 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2413 cmd->command, cmd->argument3, ret);
2417 if (!wait_for_completion_timeout(hba->uic_async_done,
2418 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2420 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2421 cmd->command, cmd->argument3);
2426 status = ufshcd_get_upmcrs(hba);
2427 if (status != PWR_LOCAL) {
2429 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2430 cmd->command, status);
2431 ret = (status != PWR_OK) ? status : -1;
2434 spin_lock_irqsave(hba->host->host_lock, flags);
2435 hba->active_uic_cmd = NULL;
2436 hba->uic_async_done = NULL;
2438 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2439 spin_unlock_irqrestore(hba->host->host_lock, flags);
2440 mutex_unlock(&hba->uic_cmd_mutex);
2446 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2447 * using DME_SET primitives.
2448 * @hba: per adapter instance
2449 * @mode: powr mode value
2451 * Returns 0 on success, non-zero value on failure
2453 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2455 struct uic_command uic_cmd = {0};
2458 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2459 ret = ufshcd_dme_set(hba,
2460 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2462 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2468 uic_cmd.command = UIC_CMD_DME_SET;
2469 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2470 uic_cmd.argument3 = mode;
2471 ufshcd_hold(hba, false);
2472 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2473 ufshcd_release(hba);
2479 static int ufshcd_link_recovery(struct ufs_hba *hba)
2482 unsigned long flags;
2484 spin_lock_irqsave(hba->host->host_lock, flags);
2485 hba->ufshcd_state = UFSHCD_STATE_RESET;
2486 ufshcd_set_eh_in_progress(hba);
2487 spin_unlock_irqrestore(hba->host->host_lock, flags);
2489 ret = ufshcd_host_reset_and_restore(hba);
2491 spin_lock_irqsave(hba->host->host_lock, flags);
2493 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2494 ufshcd_clear_eh_in_progress(hba);
2495 spin_unlock_irqrestore(hba->host->host_lock, flags);
2498 dev_err(hba->dev, "%s: link recovery failed, err %d",
2504 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2507 struct uic_command uic_cmd = {0};
2509 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2510 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2513 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2517 * If link recovery fails then return error so that caller
2518 * don't retry the hibern8 enter again.
2520 if (ufshcd_link_recovery(hba))
2527 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2529 int ret = 0, retries;
2531 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2532 ret = __ufshcd_uic_hibern8_enter(hba);
2533 if (!ret || ret == -ENOLINK)
2540 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2542 struct uic_command uic_cmd = {0};
2545 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2546 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2548 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2550 ret = ufshcd_link_recovery(hba);
2557 * ufshcd_init_pwr_info - setting the POR (power on reset)
2558 * values in hba power info
2559 * @hba: per-adapter instance
2561 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2563 hba->pwr_info.gear_rx = UFS_PWM_G1;
2564 hba->pwr_info.gear_tx = UFS_PWM_G1;
2565 hba->pwr_info.lane_rx = 1;
2566 hba->pwr_info.lane_tx = 1;
2567 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2568 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2569 hba->pwr_info.hs_rate = 0;
2573 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2574 * @hba: per-adapter instance
2576 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2578 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2580 if (hba->max_pwr_info.is_valid)
2583 pwr_info->pwr_tx = FASTAUTO_MODE;
2584 pwr_info->pwr_rx = FASTAUTO_MODE;
2585 pwr_info->hs_rate = PA_HS_MODE_B;
2587 /* Get the connected lane count */
2588 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2589 &pwr_info->lane_rx);
2590 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2591 &pwr_info->lane_tx);
2593 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2594 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2602 * First, get the maximum gears of HS speed.
2603 * If a zero value, it means there is no HSGEAR capability.
2604 * Then, get the maximum gears of PWM speed.
2606 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2607 if (!pwr_info->gear_rx) {
2608 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2609 &pwr_info->gear_rx);
2610 if (!pwr_info->gear_rx) {
2611 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2612 __func__, pwr_info->gear_rx);
2615 pwr_info->pwr_rx = SLOWAUTO_MODE;
2618 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2619 &pwr_info->gear_tx);
2620 if (!pwr_info->gear_tx) {
2621 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2622 &pwr_info->gear_tx);
2623 if (!pwr_info->gear_tx) {
2624 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2625 __func__, pwr_info->gear_tx);
2628 pwr_info->pwr_tx = SLOWAUTO_MODE;
2631 hba->max_pwr_info.is_valid = true;
2635 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2636 struct ufs_pa_layer_attr *pwr_mode)
2640 /* if already configured to the requested pwr_mode */
2641 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2642 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2643 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2644 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2645 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2646 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2647 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2648 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2653 * Configure attributes for power mode change with below.
2654 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2655 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2658 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2659 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2661 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2662 pwr_mode->pwr_rx == FAST_MODE)
2663 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2665 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2667 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2668 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2670 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2671 pwr_mode->pwr_tx == FAST_MODE)
2672 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2674 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2676 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2677 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2678 pwr_mode->pwr_rx == FAST_MODE ||
2679 pwr_mode->pwr_tx == FAST_MODE)
2680 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2683 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2684 | pwr_mode->pwr_tx);
2688 "%s: power mode change failed %d\n", __func__, ret);
2690 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2693 memcpy(&hba->pwr_info, pwr_mode,
2694 sizeof(struct ufs_pa_layer_attr));
2701 * ufshcd_config_pwr_mode - configure a new power mode
2702 * @hba: per-adapter instance
2703 * @desired_pwr_mode: desired power configuration
2705 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2706 struct ufs_pa_layer_attr *desired_pwr_mode)
2708 struct ufs_pa_layer_attr final_params = { 0 };
2711 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2712 desired_pwr_mode, &final_params);
2715 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2717 ret = ufshcd_change_power_mode(hba, &final_params);
2723 * ufshcd_complete_dev_init() - checks device readiness
2724 * hba: per-adapter instance
2726 * Set fDeviceInit flag and poll until device toggles it.
2728 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2734 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2735 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2738 "%s setting fDeviceInit flag failed with error %d\n",
2743 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2744 for (i = 0; i < 1000 && !err && flag_res; i++)
2745 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2746 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2750 "%s reading fDeviceInit flag failed with error %d\n",
2754 "%s fDeviceInit was not cleared by the device\n",
2762 * ufshcd_make_hba_operational - Make UFS controller operational
2763 * @hba: per adapter instance
2765 * To bring UFS host controller to operational state,
2766 * 1. Enable required interrupts
2767 * 2. Configure interrupt aggregation
2768 * 3. Program UTRL and UTMRL base address
2769 * 4. Configure run-stop-registers
2771 * Returns 0 on success, non-zero value on failure
2773 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2778 /* Enable required interrupts */
2779 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2781 /* Configure interrupt aggregation */
2782 if (ufshcd_is_intr_aggr_allowed(hba))
2783 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2785 ufshcd_disable_intr_aggr(hba);
2787 /* Configure UTRL and UTMRL base address registers */
2788 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2789 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2790 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2791 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2792 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2793 REG_UTP_TASK_REQ_LIST_BASE_L);
2794 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2795 REG_UTP_TASK_REQ_LIST_BASE_H);
2798 * Make sure base address and interrupt setup are updated before
2799 * enabling the run/stop registers below.
2804 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2806 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2807 if (!(ufshcd_get_lists_status(reg))) {
2808 ufshcd_enable_run_stop_reg(hba);
2811 "Host controller not ready to process requests");
2821 * ufshcd_hba_stop - Send controller to reset state
2822 * @hba: per adapter instance
2823 * @can_sleep: perform sleep or just spin
2825 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
2829 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
2830 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
2831 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
2834 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
2838 * ufshcd_hba_enable - initialize the controller
2839 * @hba: per adapter instance
2841 * The controller resets itself and controller firmware initialization
2842 * sequence kicks off. When controller is ready it will set
2843 * the Host Controller Enable bit to 1.
2845 * Returns 0 on success, non-zero value on failure
2847 static int ufshcd_hba_enable(struct ufs_hba *hba)
2852 * msleep of 1 and 5 used in this function might result in msleep(20),
2853 * but it was necessary to send the UFS FPGA to reset mode during
2854 * development and testing of this driver. msleep can be changed to
2855 * mdelay and retry count can be reduced based on the controller.
2857 if (!ufshcd_is_hba_active(hba))
2858 /* change controller state to "reset state" */
2859 ufshcd_hba_stop(hba, true);
2861 /* UniPro link is disabled at this point */
2862 ufshcd_set_link_off(hba);
2864 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
2866 /* start controller initialization sequence */
2867 ufshcd_hba_start(hba);
2870 * To initialize a UFS host controller HCE bit must be set to 1.
2871 * During initialization the HCE bit value changes from 1->0->1.
2872 * When the host controller completes initialization sequence
2873 * it sets the value of HCE bit to 1. The same HCE bit is read back
2874 * to check if the controller has completed initialization sequence.
2875 * So without this delay the value HCE = 1, set in the previous
2876 * instruction might be read back.
2877 * This delay can be changed based on the controller.
2881 /* wait for the host controller to complete initialization */
2883 while (ufshcd_is_hba_active(hba)) {
2888 "Controller enable failed\n");
2894 /* enable UIC related interrupts */
2895 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
2897 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
2902 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
2904 int tx_lanes, i, err = 0;
2907 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2910 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2912 for (i = 0; i < tx_lanes; i++) {
2914 err = ufshcd_dme_set(hba,
2915 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2916 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2919 err = ufshcd_dme_peer_set(hba,
2920 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2921 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2924 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
2925 __func__, peer, i, err);
2933 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
2935 return ufshcd_disable_tx_lcc(hba, true);
2939 * ufshcd_link_startup - Initialize unipro link startup
2940 * @hba: per adapter instance
2942 * Returns 0 for success, non-zero in case of failure
2944 static int ufshcd_link_startup(struct ufs_hba *hba)
2947 int retries = DME_LINKSTARTUP_RETRIES;
2950 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
2952 ret = ufshcd_dme_link_startup(hba);
2954 /* check if device is detected by inter-connect layer */
2955 if (!ret && !ufshcd_is_device_present(hba)) {
2956 dev_err(hba->dev, "%s: Device not present\n", __func__);
2962 * DME link lost indication is only received when link is up,
2963 * but we can't be sure if the link is up until link startup
2964 * succeeds. So reset the local Uni-Pro and try again.
2966 if (ret && ufshcd_hba_enable(hba))
2968 } while (ret && retries--);
2971 /* failed to get the link up... retire */
2974 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
2975 ret = ufshcd_disable_device_tx_lcc(hba);
2980 /* Include any host controller configuration via UIC commands */
2981 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
2985 ret = ufshcd_make_hba_operational(hba);
2988 dev_err(hba->dev, "link startup failed %d\n", ret);
2993 * ufshcd_verify_dev_init() - Verify device initialization
2994 * @hba: per-adapter instance
2996 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
2997 * device Transport Protocol (UTP) layer is ready after a reset.
2998 * If the UTP layer at the device side is not initialized, it may
2999 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3000 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3002 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3007 ufshcd_hold(hba, false);
3008 mutex_lock(&hba->dev_cmd.lock);
3009 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3010 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3013 if (!err || err == -ETIMEDOUT)
3016 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3018 mutex_unlock(&hba->dev_cmd.lock);
3019 ufshcd_release(hba);
3022 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3027 * ufshcd_set_queue_depth - set lun queue depth
3028 * @sdev: pointer to SCSI device
3030 * Read bLUQueueDepth value and activate scsi tagged command
3031 * queueing. For WLUN, queue depth is set to 1. For best-effort
3032 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3033 * value that host can queue.
3035 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3039 struct ufs_hba *hba;
3041 hba = shost_priv(sdev->host);
3043 lun_qdepth = hba->nutrs;
3044 ret = ufshcd_read_unit_desc_param(hba,
3045 ufshcd_scsi_to_upiu_lun(sdev->lun),
3046 UNIT_DESC_PARAM_LU_Q_DEPTH,
3048 sizeof(lun_qdepth));
3050 /* Some WLUN doesn't support unit descriptor */
3051 if (ret == -EOPNOTSUPP)
3053 else if (!lun_qdepth)
3054 /* eventually, we can figure out the real queue depth */
3055 lun_qdepth = hba->nutrs;
3057 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3059 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3060 __func__, lun_qdepth);
3061 scsi_change_queue_depth(sdev, lun_qdepth);
3065 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3066 * @hba: per-adapter instance
3067 * @lun: UFS device lun id
3068 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3070 * Returns 0 in case of success and b_lu_write_protect status would be returned
3071 * @b_lu_write_protect parameter.
3072 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3073 * Returns -EINVAL in case of invalid parameters passed to this function.
3075 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3077 u8 *b_lu_write_protect)
3081 if (!b_lu_write_protect)
3084 * According to UFS device spec, RPMB LU can't be write
3085 * protected so skip reading bLUWriteProtect parameter for
3086 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3088 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3091 ret = ufshcd_read_unit_desc_param(hba,
3093 UNIT_DESC_PARAM_LU_WR_PROTECT,
3095 sizeof(*b_lu_write_protect));
3100 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3102 * @hba: per-adapter instance
3103 * @sdev: pointer to SCSI device
3106 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3107 struct scsi_device *sdev)
3109 if (hba->dev_info.f_power_on_wp_en &&
3110 !hba->dev_info.is_lu_power_on_wp) {
3111 u8 b_lu_write_protect;
3113 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3114 &b_lu_write_protect) &&
3115 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3116 hba->dev_info.is_lu_power_on_wp = true;
3121 * ufshcd_slave_alloc - handle initial SCSI device configurations
3122 * @sdev: pointer to SCSI device
3126 static int ufshcd_slave_alloc(struct scsi_device *sdev)
3128 struct ufs_hba *hba;
3130 hba = shost_priv(sdev->host);
3132 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3133 sdev->use_10_for_ms = 1;
3135 /* allow SCSI layer to restart the device in case of errors */
3136 sdev->allow_restart = 1;
3138 /* REPORT SUPPORTED OPERATION CODES is not supported */
3139 sdev->no_report_opcodes = 1;
3142 ufshcd_set_queue_depth(sdev);
3144 ufshcd_get_lu_power_on_wp_status(hba, sdev);
3150 * ufshcd_change_queue_depth - change queue depth
3151 * @sdev: pointer to SCSI device
3152 * @depth: required depth to set
3154 * Change queue depth and make sure the max. limits are not crossed.
3156 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
3158 struct ufs_hba *hba = shost_priv(sdev->host);
3160 if (depth > hba->nutrs)
3162 return scsi_change_queue_depth(sdev, depth);
3166 * ufshcd_slave_configure - adjust SCSI device configurations
3167 * @sdev: pointer to SCSI device
3169 static int ufshcd_slave_configure(struct scsi_device *sdev)
3171 struct request_queue *q = sdev->request_queue;
3173 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3174 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3180 * ufshcd_slave_destroy - remove SCSI device configurations
3181 * @sdev: pointer to SCSI device
3183 static void ufshcd_slave_destroy(struct scsi_device *sdev)
3185 struct ufs_hba *hba;
3187 hba = shost_priv(sdev->host);
3188 /* Drop the reference as it won't be needed anymore */
3189 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3190 unsigned long flags;
3192 spin_lock_irqsave(hba->host->host_lock, flags);
3193 hba->sdev_ufs_device = NULL;
3194 spin_unlock_irqrestore(hba->host->host_lock, flags);
3199 * ufshcd_task_req_compl - handle task management request completion
3200 * @hba: per adapter instance
3201 * @index: index of the completed request
3202 * @resp: task management service response
3204 * Returns non-zero value on error, zero on success
3206 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3208 struct utp_task_req_desc *task_req_descp;
3209 struct utp_upiu_task_rsp *task_rsp_upiup;
3210 unsigned long flags;
3214 spin_lock_irqsave(hba->host->host_lock, flags);
3216 /* Clear completed tasks from outstanding_tasks */
3217 __clear_bit(index, &hba->outstanding_tasks);
3219 task_req_descp = hba->utmrdl_base_addr;
3220 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3222 if (ocs_value == OCS_SUCCESS) {
3223 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3224 task_req_descp[index].task_rsp_upiu;
3225 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
3226 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
3228 *resp = (u8)task_result;
3230 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3231 __func__, ocs_value);
3233 spin_unlock_irqrestore(hba->host->host_lock, flags);
3239 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3240 * @lrb: pointer to local reference block of completed command
3241 * @scsi_status: SCSI command status
3243 * Returns value base on SCSI command status
3246 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3250 switch (scsi_status) {
3251 case SAM_STAT_CHECK_CONDITION:
3252 ufshcd_copy_sense_data(lrbp);
3254 result |= DID_OK << 16 |
3255 COMMAND_COMPLETE << 8 |
3258 case SAM_STAT_TASK_SET_FULL:
3260 case SAM_STAT_TASK_ABORTED:
3261 ufshcd_copy_sense_data(lrbp);
3262 result |= scsi_status;
3265 result |= DID_ERROR << 16;
3267 } /* end of switch */
3273 * ufshcd_transfer_rsp_status - Get overall status of the response
3274 * @hba: per adapter instance
3275 * @lrb: pointer to local reference block of completed command
3277 * Returns result of the command to notify SCSI midlayer
3280 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3286 /* overall command status of utrd */
3287 ocs = ufshcd_get_tr_ocs(lrbp);
3291 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3294 case UPIU_TRANSACTION_RESPONSE:
3296 * get the response UPIU result to extract
3297 * the SCSI command status
3299 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3302 * get the result based on SCSI status response
3303 * to notify the SCSI midlayer of the command status
3305 scsi_status = result & MASK_SCSI_STATUS;
3306 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3309 * Currently we are only supporting BKOPs exception
3310 * events hence we can ignore BKOPs exception event
3311 * during power management callbacks. BKOPs exception
3312 * event is not expected to be raised in runtime suspend
3313 * callback as it allows the urgent bkops.
3314 * During system suspend, we are anyway forcefully
3315 * disabling the bkops and if urgent bkops is needed
3316 * it will be enabled on system resume. Long term
3317 * solution could be to abort the system suspend if
3318 * UFS device needs urgent BKOPs.
3320 if (!hba->pm_op_in_progress &&
3321 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3322 schedule_work(&hba->eeh_work);
3324 case UPIU_TRANSACTION_REJECT_UPIU:
3325 /* TODO: handle Reject UPIU Response */
3326 result = DID_ERROR << 16;
3328 "Reject UPIU not fully implemented\n");
3331 result = DID_ERROR << 16;
3333 "Unexpected request response code = %x\n",
3339 result |= DID_ABORT << 16;
3341 case OCS_INVALID_COMMAND_STATUS:
3342 result |= DID_REQUEUE << 16;
3344 case OCS_INVALID_CMD_TABLE_ATTR:
3345 case OCS_INVALID_PRDT_ATTR:
3346 case OCS_MISMATCH_DATA_BUF_SIZE:
3347 case OCS_MISMATCH_RESP_UPIU_SIZE:
3348 case OCS_PEER_COMM_FAILURE:
3349 case OCS_FATAL_ERROR:
3351 result |= DID_ERROR << 16;
3353 "OCS error from controller = %x\n", ocs);
3355 } /* end of switch */
3361 * ufshcd_uic_cmd_compl - handle completion of uic command
3362 * @hba: per adapter instance
3363 * @intr_status: interrupt status generated by the controller
3365 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3367 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3368 hba->active_uic_cmd->argument2 |=
3369 ufshcd_get_uic_cmd_result(hba);
3370 hba->active_uic_cmd->argument3 =
3371 ufshcd_get_dme_attr_val(hba);
3372 complete(&hba->active_uic_cmd->done);
3375 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3376 complete(hba->uic_async_done);
3380 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3381 * @hba: per adapter instance
3383 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3385 struct ufshcd_lrb *lrbp;
3386 struct scsi_cmnd *cmd;
3387 unsigned long completed_reqs;
3392 /* Resetting interrupt aggregation counters first and reading the
3393 * DOOR_BELL afterward allows us to handle all the completed requests.
3394 * In order to prevent other interrupts starvation the DB is read once
3395 * after reset. The down side of this solution is the possibility of
3396 * false interrupt if device completes another request after resetting
3397 * aggregation and before reading the DB.
3399 if (ufshcd_is_intr_aggr_allowed(hba))
3400 ufshcd_reset_intr_aggr(hba);
3402 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3403 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3405 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3406 lrbp = &hba->lrb[index];
3409 result = ufshcd_transfer_rsp_status(hba, lrbp);
3410 scsi_dma_unmap(cmd);
3411 cmd->result = result;
3412 /* Mark completed command as NULL in LRB */
3414 clear_bit_unlock(index, &hba->lrb_in_use);
3415 /* Do not touch lrbp after scsi done */
3416 cmd->scsi_done(cmd);
3417 __ufshcd_release(hba);
3418 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3419 if (hba->dev_cmd.complete)
3420 complete(hba->dev_cmd.complete);
3424 /* clear corresponding bits of completed commands */
3425 hba->outstanding_reqs ^= completed_reqs;
3427 ufshcd_clk_scaling_update_busy(hba);
3429 /* we might have free'd some tags above */
3430 wake_up(&hba->dev_cmd.tag_wq);
3434 * ufshcd_disable_ee - disable exception event
3435 * @hba: per-adapter instance
3436 * @mask: exception event to disable
3438 * Disables exception event in the device so that the EVENT_ALERT
3441 * Returns zero on success, non-zero error value on failure.
3443 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3448 if (!(hba->ee_ctrl_mask & mask))
3451 val = hba->ee_ctrl_mask & ~mask;
3452 val &= 0xFFFF; /* 2 bytes */
3453 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3454 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3456 hba->ee_ctrl_mask &= ~mask;
3462 * ufshcd_enable_ee - enable exception event
3463 * @hba: per-adapter instance
3464 * @mask: exception event to enable
3466 * Enable corresponding exception event in the device to allow
3467 * device to alert host in critical scenarios.
3469 * Returns zero on success, non-zero error value on failure.
3471 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3476 if (hba->ee_ctrl_mask & mask)
3479 val = hba->ee_ctrl_mask | mask;
3480 val &= 0xFFFF; /* 2 bytes */
3481 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3482 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3484 hba->ee_ctrl_mask |= mask;
3490 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3491 * @hba: per-adapter instance
3493 * Allow device to manage background operations on its own. Enabling
3494 * this might lead to inconsistent latencies during normal data transfers
3495 * as the device is allowed to manage its own way of handling background
3498 * Returns zero on success, non-zero on failure.
3500 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3504 if (hba->auto_bkops_enabled)
3507 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3508 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3510 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3515 hba->auto_bkops_enabled = true;
3517 /* No need of URGENT_BKOPS exception from the device */
3518 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3520 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3527 * ufshcd_disable_auto_bkops - block device in doing background operations
3528 * @hba: per-adapter instance
3530 * Disabling background operations improves command response latency but
3531 * has drawback of device moving into critical state where the device is
3532 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3533 * host is idle so that BKOPS are managed effectively without any negative
3536 * Returns zero on success, non-zero on failure.
3538 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3542 if (!hba->auto_bkops_enabled)
3546 * If host assisted BKOPs is to be enabled, make sure
3547 * urgent bkops exception is allowed.
3549 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3551 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3556 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3557 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3559 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3561 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3565 hba->auto_bkops_enabled = false;
3571 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3572 * @hba: per adapter instance
3574 * After a device reset the device may toggle the BKOPS_EN flag
3575 * to default value. The s/w tracking variables should be updated
3576 * as well. Do this by forcing enable of auto bkops.
3578 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3580 hba->auto_bkops_enabled = false;
3581 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3582 ufshcd_enable_auto_bkops(hba);
3585 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3587 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3588 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3592 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3593 * @hba: per-adapter instance
3594 * @status: bkops_status value
3596 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3597 * flag in the device to permit background operations if the device
3598 * bkops_status is greater than or equal to "status" argument passed to
3599 * this function, disable otherwise.
3601 * Returns 0 for success, non-zero in case of failure.
3603 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3604 * to know whether auto bkops is enabled or disabled after this function
3605 * returns control to it.
3607 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3608 enum bkops_status status)
3611 u32 curr_status = 0;
3613 err = ufshcd_get_bkops_status(hba, &curr_status);
3615 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3618 } else if (curr_status > BKOPS_STATUS_MAX) {
3619 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3620 __func__, curr_status);
3625 if (curr_status >= status)
3626 err = ufshcd_enable_auto_bkops(hba);
3628 err = ufshcd_disable_auto_bkops(hba);
3634 * ufshcd_urgent_bkops - handle urgent bkops exception event
3635 * @hba: per-adapter instance
3637 * Enable fBackgroundOpsEn flag in the device to permit background
3640 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3641 * and negative error value for any other failure.
3643 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3645 return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3648 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3650 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3651 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3655 * ufshcd_exception_event_handler - handle exceptions raised by device
3656 * @work: pointer to work data
3658 * Read bExceptionEventStatus attribute from the device and handle the
3659 * exception event accordingly.
3661 static void ufshcd_exception_event_handler(struct work_struct *work)
3663 struct ufs_hba *hba;
3666 hba = container_of(work, struct ufs_hba, eeh_work);
3668 pm_runtime_get_sync(hba->dev);
3669 err = ufshcd_get_ee_status(hba, &status);
3671 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3676 status &= hba->ee_ctrl_mask;
3677 if (status & MASK_EE_URGENT_BKOPS) {
3678 err = ufshcd_urgent_bkops(hba);
3680 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3684 pm_runtime_put_sync(hba->dev);
3689 * ufshcd_err_handler - handle UFS errors that require s/w attention
3690 * @work: pointer to work structure
3692 static void ufshcd_err_handler(struct work_struct *work)
3694 struct ufs_hba *hba;
3695 unsigned long flags;
3701 hba = container_of(work, struct ufs_hba, eh_work);
3703 pm_runtime_get_sync(hba->dev);
3704 ufshcd_hold(hba, false);
3706 spin_lock_irqsave(hba->host->host_lock, flags);
3707 if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
3708 spin_unlock_irqrestore(hba->host->host_lock, flags);
3712 hba->ufshcd_state = UFSHCD_STATE_RESET;
3713 ufshcd_set_eh_in_progress(hba);
3715 /* Complete requests that have door-bell cleared by h/w */
3716 ufshcd_transfer_req_compl(hba);
3717 ufshcd_tmc_handler(hba);
3718 spin_unlock_irqrestore(hba->host->host_lock, flags);
3720 /* Clear pending transfer requests */
3721 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs)
3722 if (ufshcd_clear_cmd(hba, tag))
3723 err_xfer |= 1 << tag;
3725 /* Clear pending task management requests */
3726 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs)
3727 if (ufshcd_clear_tm_cmd(hba, tag))
3730 /* Complete the requests that are cleared by s/w */
3731 spin_lock_irqsave(hba->host->host_lock, flags);
3732 ufshcd_transfer_req_compl(hba);
3733 ufshcd_tmc_handler(hba);
3734 spin_unlock_irqrestore(hba->host->host_lock, flags);
3736 /* Fatal errors need reset */
3737 if (err_xfer || err_tm || (hba->saved_err & INT_FATAL_ERRORS) ||
3738 ((hba->saved_err & UIC_ERROR) &&
3739 (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR))) {
3740 err = ufshcd_reset_and_restore(hba);
3742 dev_err(hba->dev, "%s: reset and restore failed\n",
3744 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3747 * Inform scsi mid-layer that we did reset and allow to handle
3748 * Unit Attention properly.
3750 scsi_report_bus_reset(hba->host, 0);
3752 hba->saved_uic_err = 0;
3754 ufshcd_clear_eh_in_progress(hba);
3757 scsi_unblock_requests(hba->host);
3758 ufshcd_release(hba);
3759 pm_runtime_put_sync(hba->dev);
3763 * ufshcd_update_uic_error - check and set fatal UIC error flags.
3764 * @hba: per-adapter instance
3766 static void ufshcd_update_uic_error(struct ufs_hba *hba)
3770 /* PA_INIT_ERROR is fatal and needs UIC reset */
3771 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
3772 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
3773 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
3775 /* UIC NL/TL/DME errors needs software retry */
3776 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
3778 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
3780 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
3782 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
3784 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
3786 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
3788 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
3789 __func__, hba->uic_error);
3793 * ufshcd_check_errors - Check for errors that need s/w attention
3794 * @hba: per-adapter instance
3796 static void ufshcd_check_errors(struct ufs_hba *hba)
3798 bool queue_eh_work = false;
3800 if (hba->errors & INT_FATAL_ERRORS)
3801 queue_eh_work = true;
3803 if (hba->errors & UIC_ERROR) {
3805 ufshcd_update_uic_error(hba);
3807 queue_eh_work = true;
3810 if (queue_eh_work) {
3811 /* handle fatal errors only when link is functional */
3812 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
3813 /* block commands from scsi mid-layer */
3814 scsi_block_requests(hba->host);
3816 /* transfer error masks to sticky bits */
3817 hba->saved_err |= hba->errors;
3818 hba->saved_uic_err |= hba->uic_error;
3820 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3821 schedule_work(&hba->eh_work);
3825 * if (!queue_eh_work) -
3826 * Other errors are either non-fatal where host recovers
3827 * itself without s/w intervention or errors that will be
3828 * handled by the SCSI core layer.
3833 * ufshcd_tmc_handler - handle task management function completion
3834 * @hba: per adapter instance
3836 static void ufshcd_tmc_handler(struct ufs_hba *hba)
3840 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
3841 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
3842 wake_up(&hba->tm_wq);
3846 * ufshcd_sl_intr - Interrupt service routine
3847 * @hba: per adapter instance
3848 * @intr_status: contains interrupts generated by the controller
3850 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
3852 hba->errors = UFSHCD_ERROR_MASK & intr_status;
3854 ufshcd_check_errors(hba);
3856 if (intr_status & UFSHCD_UIC_MASK)
3857 ufshcd_uic_cmd_compl(hba, intr_status);
3859 if (intr_status & UTP_TASK_REQ_COMPL)
3860 ufshcd_tmc_handler(hba);
3862 if (intr_status & UTP_TRANSFER_REQ_COMPL)
3863 ufshcd_transfer_req_compl(hba);
3867 * ufshcd_intr - Main interrupt service routine
3869 * @__hba: pointer to adapter instance
3871 * Returns IRQ_HANDLED - If interrupt is valid
3872 * IRQ_NONE - If invalid interrupt
3874 static irqreturn_t ufshcd_intr(int irq, void *__hba)
3876 u32 intr_status, enabled_intr_status;
3877 irqreturn_t retval = IRQ_NONE;
3878 struct ufs_hba *hba = __hba;
3880 spin_lock(hba->host->host_lock);
3881 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
3882 enabled_intr_status =
3883 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
3886 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
3888 if (enabled_intr_status) {
3889 ufshcd_sl_intr(hba, enabled_intr_status);
3890 retval = IRQ_HANDLED;
3892 spin_unlock(hba->host->host_lock);
3896 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
3899 u32 mask = 1 << tag;
3900 unsigned long flags;
3902 if (!test_bit(tag, &hba->outstanding_tasks))
3905 spin_lock_irqsave(hba->host->host_lock, flags);
3906 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
3907 spin_unlock_irqrestore(hba->host->host_lock, flags);
3909 /* poll for max. 1 sec to clear door bell register by h/w */
3910 err = ufshcd_wait_for_register(hba,
3911 REG_UTP_TASK_REQ_DOOR_BELL,
3912 mask, 0, 1000, 1000, true);
3918 * ufshcd_issue_tm_cmd - issues task management commands to controller
3919 * @hba: per adapter instance
3920 * @lun_id: LUN ID to which TM command is sent
3921 * @task_id: task ID to which the TM command is applicable
3922 * @tm_function: task management function opcode
3923 * @tm_response: task management service response return value
3925 * Returns non-zero value on error, zero on success.
3927 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
3928 u8 tm_function, u8 *tm_response)
3930 struct utp_task_req_desc *task_req_descp;
3931 struct utp_upiu_task_req *task_req_upiup;
3932 struct Scsi_Host *host;
3933 unsigned long flags;
3941 * Get free slot, sleep if slots are unavailable.
3942 * Even though we use wait_event() which sleeps indefinitely,
3943 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
3945 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
3946 ufshcd_hold(hba, false);
3948 spin_lock_irqsave(host->host_lock, flags);
3949 task_req_descp = hba->utmrdl_base_addr;
3950 task_req_descp += free_slot;
3952 /* Configure task request descriptor */
3953 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
3954 task_req_descp->header.dword_2 =
3955 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
3957 /* Configure task request UPIU */
3959 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
3960 task_tag = hba->nutrs + free_slot;
3961 task_req_upiup->header.dword_0 =
3962 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
3964 task_req_upiup->header.dword_1 =
3965 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
3967 * The host shall provide the same value for LUN field in the basic
3968 * header and for Input Parameter.
3970 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
3971 task_req_upiup->input_param2 = cpu_to_be32(task_id);
3973 /* send command to the controller */
3974 __set_bit(free_slot, &hba->outstanding_tasks);
3976 /* Make sure descriptors are ready before ringing the task doorbell */
3979 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
3981 spin_unlock_irqrestore(host->host_lock, flags);
3983 /* wait until the task management command is completed */
3984 err = wait_event_timeout(hba->tm_wq,
3985 test_bit(free_slot, &hba->tm_condition),
3986 msecs_to_jiffies(TM_CMD_TIMEOUT));
3988 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
3989 __func__, tm_function);
3990 if (ufshcd_clear_tm_cmd(hba, free_slot))
3991 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
3992 __func__, free_slot);
3995 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
3998 clear_bit(free_slot, &hba->tm_condition);
3999 ufshcd_put_tm_slot(hba, free_slot);
4000 wake_up(&hba->tm_tag_wq);
4002 ufshcd_release(hba);
4007 * ufshcd_eh_device_reset_handler - device reset handler registered to
4009 * @cmd: SCSI command pointer
4011 * Returns SUCCESS/FAILED
4013 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
4015 struct Scsi_Host *host;
4016 struct ufs_hba *hba;
4021 struct ufshcd_lrb *lrbp;
4022 unsigned long flags;
4024 host = cmd->device->host;
4025 hba = shost_priv(host);
4026 tag = cmd->request->tag;
4028 lrbp = &hba->lrb[tag];
4029 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4030 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4036 /* clear the commands that were pending for corresponding LUN */
4037 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4038 if (hba->lrb[pos].lun == lrbp->lun) {
4039 err = ufshcd_clear_cmd(hba, pos);
4044 spin_lock_irqsave(host->host_lock, flags);
4045 ufshcd_transfer_req_compl(hba);
4046 spin_unlock_irqrestore(host->host_lock, flags);
4051 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4058 * ufshcd_abort - abort a specific command
4059 * @cmd: SCSI command pointer
4061 * Abort the pending command in device by sending UFS_ABORT_TASK task management
4062 * command, and in host controller by clearing the door-bell register. There can
4063 * be race between controller sending the command to the device while abort is
4064 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4065 * really issued and then try to abort it.
4067 * Returns SUCCESS/FAILED
4069 static int ufshcd_abort(struct scsi_cmnd *cmd)
4071 struct Scsi_Host *host;
4072 struct ufs_hba *hba;
4073 unsigned long flags;
4078 struct ufshcd_lrb *lrbp;
4081 host = cmd->device->host;
4082 hba = shost_priv(host);
4083 tag = cmd->request->tag;
4084 if (!ufshcd_valid_tag(hba, tag)) {
4086 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4087 __func__, tag, cmd, cmd->request);
4091 ufshcd_hold(hba, false);
4092 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4093 /* If command is already aborted/completed, return SUCCESS */
4094 if (!(test_bit(tag, &hba->outstanding_reqs))) {
4096 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4097 __func__, tag, hba->outstanding_reqs, reg);
4101 if (!(reg & (1 << tag))) {
4103 "%s: cmd was completed, but without a notifying intr, tag = %d",
4107 lrbp = &hba->lrb[tag];
4108 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4109 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4110 UFS_QUERY_TASK, &resp);
4111 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4112 /* cmd pending in the device */
4114 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4116 * cmd not pending in the device, check if it is
4119 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4120 if (reg & (1 << tag)) {
4121 /* sleep for max. 200us to stabilize */
4122 usleep_range(100, 200);
4125 /* command completed already */
4129 err = resp; /* service response error */
4139 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4140 UFS_ABORT_TASK, &resp);
4141 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4143 err = resp; /* service response error */
4147 err = ufshcd_clear_cmd(hba, tag);
4151 scsi_dma_unmap(cmd);
4153 spin_lock_irqsave(host->host_lock, flags);
4154 ufshcd_outstanding_req_clear(hba, tag);
4155 hba->lrb[tag].cmd = NULL;
4156 spin_unlock_irqrestore(host->host_lock, flags);
4158 clear_bit_unlock(tag, &hba->lrb_in_use);
4159 wake_up(&hba->dev_cmd.tag_wq);
4165 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4170 * This ufshcd_release() corresponds to the original scsi cmd that got
4171 * aborted here (as we won't get any IRQ for it).
4173 ufshcd_release(hba);
4178 * ufshcd_host_reset_and_restore - reset and restore host controller
4179 * @hba: per-adapter instance
4181 * Note that host controller reset may issue DME_RESET to
4182 * local and remote (device) Uni-Pro stack and the attributes
4183 * are reset to default state.
4185 * Returns zero on success, non-zero on failure
4187 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4190 unsigned long flags;
4192 /* Reset the host controller */
4193 spin_lock_irqsave(hba->host->host_lock, flags);
4194 ufshcd_hba_stop(hba, false);
4195 spin_unlock_irqrestore(hba->host->host_lock, flags);
4197 err = ufshcd_hba_enable(hba);
4201 /* Establish the link again and restore the device */
4202 err = ufshcd_probe_hba(hba);
4204 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
4208 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4214 * ufshcd_reset_and_restore - reset and re-initialize host/device
4215 * @hba: per-adapter instance
4217 * Reset and recover device, host and re-establish link. This
4218 * is helpful to recover the communication in fatal error conditions.
4220 * Returns zero on success, non-zero on failure
4222 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4225 unsigned long flags;
4226 int retries = MAX_HOST_RESET_RETRIES;
4229 err = ufshcd_host_reset_and_restore(hba);
4230 } while (err && --retries);
4233 * After reset the door-bell might be cleared, complete
4234 * outstanding requests in s/w here.
4236 spin_lock_irqsave(hba->host->host_lock, flags);
4237 ufshcd_transfer_req_compl(hba);
4238 ufshcd_tmc_handler(hba);
4239 spin_unlock_irqrestore(hba->host->host_lock, flags);
4245 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4246 * @cmd - SCSI command pointer
4248 * Returns SUCCESS/FAILED
4250 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4253 unsigned long flags;
4254 struct ufs_hba *hba;
4256 hba = shost_priv(cmd->device->host);
4258 ufshcd_hold(hba, false);
4260 * Check if there is any race with fatal error handling.
4261 * If so, wait for it to complete. Even though fatal error
4262 * handling does reset and restore in some cases, don't assume
4263 * anything out of it. We are just avoiding race here.
4266 spin_lock_irqsave(hba->host->host_lock, flags);
4267 if (!(work_pending(&hba->eh_work) ||
4268 hba->ufshcd_state == UFSHCD_STATE_RESET))
4270 spin_unlock_irqrestore(hba->host->host_lock, flags);
4271 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4272 flush_work(&hba->eh_work);
4275 hba->ufshcd_state = UFSHCD_STATE_RESET;
4276 ufshcd_set_eh_in_progress(hba);
4277 spin_unlock_irqrestore(hba->host->host_lock, flags);
4279 err = ufshcd_reset_and_restore(hba);
4281 spin_lock_irqsave(hba->host->host_lock, flags);
4284 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4287 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4289 ufshcd_clear_eh_in_progress(hba);
4290 spin_unlock_irqrestore(hba->host->host_lock, flags);
4292 ufshcd_release(hba);
4297 * ufshcd_get_max_icc_level - calculate the ICC level
4298 * @sup_curr_uA: max. current supported by the regulator
4299 * @start_scan: row at the desc table to start scan from
4300 * @buff: power descriptor buffer
4302 * Returns calculated max ICC level for specific regulator
4304 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4311 for (i = start_scan; i >= 0; i--) {
4312 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4313 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4314 ATTR_ICC_LVL_UNIT_OFFSET;
4315 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4317 case UFSHCD_NANO_AMP:
4318 curr_uA = curr_uA / 1000;
4320 case UFSHCD_MILI_AMP:
4321 curr_uA = curr_uA * 1000;
4324 curr_uA = curr_uA * 1000 * 1000;
4326 case UFSHCD_MICRO_AMP:
4330 if (sup_curr_uA >= curr_uA)
4335 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4342 * ufshcd_calc_icc_level - calculate the max ICC level
4343 * In case regulators are not initialized we'll return 0
4344 * @hba: per-adapter instance
4345 * @desc_buf: power descriptor buffer to extract ICC levels from.
4346 * @len: length of desc_buff
4348 * Returns calculated ICC level
4350 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4351 u8 *desc_buf, int len)
4355 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4356 !hba->vreg_info.vccq2) {
4358 "%s: Regulator capability was not set, actvIccLevel=%d",
4359 __func__, icc_level);
4363 if (hba->vreg_info.vcc)
4364 icc_level = ufshcd_get_max_icc_level(
4365 hba->vreg_info.vcc->max_uA,
4366 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4367 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4369 if (hba->vreg_info.vccq)
4370 icc_level = ufshcd_get_max_icc_level(
4371 hba->vreg_info.vccq->max_uA,
4373 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4375 if (hba->vreg_info.vccq2)
4376 icc_level = ufshcd_get_max_icc_level(
4377 hba->vreg_info.vccq2->max_uA,
4379 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4384 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4387 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4388 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4390 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4393 "%s: Failed reading power descriptor.len = %d ret = %d",
4394 __func__, buff_len, ret);
4398 hba->init_prefetch_data.icc_level =
4399 ufshcd_find_max_sup_active_icc_level(hba,
4400 desc_buf, buff_len);
4401 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4402 __func__, hba->init_prefetch_data.icc_level);
4404 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4405 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4406 &hba->init_prefetch_data.icc_level);
4410 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4411 __func__, hba->init_prefetch_data.icc_level , ret);
4416 * ufshcd_scsi_add_wlus - Adds required W-LUs
4417 * @hba: per-adapter instance
4419 * UFS device specification requires the UFS devices to support 4 well known
4421 * "REPORT_LUNS" (address: 01h)
4422 * "UFS Device" (address: 50h)
4423 * "RPMB" (address: 44h)
4424 * "BOOT" (address: 30h)
4425 * UFS device's power management needs to be controlled by "POWER CONDITION"
4426 * field of SSU (START STOP UNIT) command. But this "power condition" field
4427 * will take effect only when its sent to "UFS device" well known logical unit
4428 * hence we require the scsi_device instance to represent this logical unit in
4429 * order for the UFS host driver to send the SSU command for power management.
4431 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4432 * Block) LU so user space process can control this LU. User space may also
4433 * want to have access to BOOT LU.
4435 * This function adds scsi device instances for each of all well known LUs
4436 * (except "REPORT LUNS" LU).
4438 * Returns zero on success (all required W-LUs are added successfully),
4439 * non-zero error value on failure (if failed to add any of the required W-LU).
4441 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4444 struct scsi_device *sdev_rpmb;
4445 struct scsi_device *sdev_boot;
4447 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4448 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4449 if (IS_ERR(hba->sdev_ufs_device)) {
4450 ret = PTR_ERR(hba->sdev_ufs_device);
4451 hba->sdev_ufs_device = NULL;
4454 scsi_device_put(hba->sdev_ufs_device);
4456 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4457 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4458 if (IS_ERR(sdev_boot)) {
4459 ret = PTR_ERR(sdev_boot);
4460 goto remove_sdev_ufs_device;
4462 scsi_device_put(sdev_boot);
4464 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4465 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4466 if (IS_ERR(sdev_rpmb)) {
4467 ret = PTR_ERR(sdev_rpmb);
4468 goto remove_sdev_boot;
4470 scsi_device_put(sdev_rpmb);
4474 scsi_remove_device(sdev_boot);
4475 remove_sdev_ufs_device:
4476 scsi_remove_device(hba->sdev_ufs_device);
4482 * ufshcd_probe_hba - probe hba to detect device and initialize
4483 * @hba: per-adapter instance
4485 * Execute link-startup and verify device initialization
4487 static int ufshcd_probe_hba(struct ufs_hba *hba)
4491 ret = ufshcd_link_startup(hba);
4495 ufshcd_init_pwr_info(hba);
4497 /* UniPro link is active now */
4498 ufshcd_set_link_active(hba);
4500 ret = ufshcd_verify_dev_init(hba);
4504 ret = ufshcd_complete_dev_init(hba);
4508 /* UFS device is also active now */
4509 ufshcd_set_ufs_dev_active(hba);
4510 ufshcd_force_reset_auto_bkops(hba);
4511 hba->wlun_dev_clr_ua = true;
4513 if (ufshcd_get_max_pwr_mode(hba)) {
4515 "%s: Failed getting max supported power mode\n",
4518 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4520 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4524 /* set the state as operational after switching to desired gear */
4525 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4527 * If we are in error handling context or in power management callbacks
4528 * context, no need to scan the host
4530 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4533 /* clear any previous UFS device information */
4534 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
4535 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4536 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
4537 hba->dev_info.f_power_on_wp_en = flag;
4539 if (!hba->is_init_prefetch)
4540 ufshcd_init_icc_levels(hba);
4542 /* Add required well known logical units to scsi mid layer */
4543 if (ufshcd_scsi_add_wlus(hba))
4546 scsi_scan_host(hba->host);
4547 pm_runtime_put_sync(hba->dev);
4550 if (!hba->is_init_prefetch)
4551 hba->is_init_prefetch = true;
4553 /* Resume devfreq after UFS device is detected */
4554 if (ufshcd_is_clkscaling_enabled(hba))
4555 devfreq_resume_device(hba->devfreq);
4559 * If we failed to initialize the device or the device is not
4560 * present, turn off the power/clocks etc.
4562 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4563 pm_runtime_put_sync(hba->dev);
4564 ufshcd_hba_exit(hba);
4571 * ufshcd_async_scan - asynchronous execution for probing hba
4572 * @data: data pointer to pass to this function
4573 * @cookie: cookie data
4575 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4577 struct ufs_hba *hba = (struct ufs_hba *)data;
4579 ufshcd_probe_hba(hba);
4582 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
4584 unsigned long flags;
4585 struct Scsi_Host *host;
4586 struct ufs_hba *hba;
4590 if (!scmd || !scmd->device || !scmd->device->host)
4591 return BLK_EH_NOT_HANDLED;
4593 host = scmd->device->host;
4594 hba = shost_priv(host);
4596 return BLK_EH_NOT_HANDLED;
4598 spin_lock_irqsave(host->host_lock, flags);
4600 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
4601 if (hba->lrb[index].cmd == scmd) {
4607 spin_unlock_irqrestore(host->host_lock, flags);
4610 * Bypass SCSI error handling and reset the block layer timer if this
4611 * SCSI command was not actually dispatched to UFS driver, otherwise
4612 * let SCSI layer handle the error as usual.
4614 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
4617 static struct scsi_host_template ufshcd_driver_template = {
4618 .module = THIS_MODULE,
4620 .proc_name = UFSHCD,
4621 .queuecommand = ufshcd_queuecommand,
4622 .slave_alloc = ufshcd_slave_alloc,
4623 .slave_configure = ufshcd_slave_configure,
4624 .slave_destroy = ufshcd_slave_destroy,
4625 .change_queue_depth = ufshcd_change_queue_depth,
4626 .eh_abort_handler = ufshcd_abort,
4627 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4628 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
4629 .eh_timed_out = ufshcd_eh_timed_out,
4631 .sg_tablesize = SG_ALL,
4632 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
4633 .can_queue = UFSHCD_CAN_QUEUE,
4634 .max_host_blocked = 1,
4635 .track_queue_depth = 1,
4638 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4646 ret = regulator_set_load(vreg->reg, ua);
4648 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4649 __func__, vreg->name, ua, ret);
4655 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
4656 struct ufs_vreg *vreg)
4658 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
4661 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
4662 struct ufs_vreg *vreg)
4664 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
4667 static int ufshcd_config_vreg(struct device *dev,
4668 struct ufs_vreg *vreg, bool on)
4671 struct regulator *reg = vreg->reg;
4672 const char *name = vreg->name;
4673 int min_uV, uA_load;
4677 if (regulator_count_voltages(reg) > 0) {
4678 min_uV = on ? vreg->min_uV : 0;
4679 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
4681 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
4682 __func__, name, ret);
4686 uA_load = on ? vreg->max_uA : 0;
4687 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
4695 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
4699 if (!vreg || vreg->enabled)
4702 ret = ufshcd_config_vreg(dev, vreg, true);
4704 ret = regulator_enable(vreg->reg);
4707 vreg->enabled = true;
4709 dev_err(dev, "%s: %s enable failed, err=%d\n",
4710 __func__, vreg->name, ret);
4715 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
4719 if (!vreg || !vreg->enabled)
4722 ret = regulator_disable(vreg->reg);
4725 /* ignore errors on applying disable config */
4726 ufshcd_config_vreg(dev, vreg, false);
4727 vreg->enabled = false;
4729 dev_err(dev, "%s: %s disable failed, err=%d\n",
4730 __func__, vreg->name, ret);
4736 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
4739 struct device *dev = hba->dev;
4740 struct ufs_vreg_info *info = &hba->vreg_info;
4745 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
4749 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
4753 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
4759 ufshcd_toggle_vreg(dev, info->vccq2, false);
4760 ufshcd_toggle_vreg(dev, info->vccq, false);
4761 ufshcd_toggle_vreg(dev, info->vcc, false);
4766 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
4768 struct ufs_vreg_info *info = &hba->vreg_info;
4771 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
4776 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
4783 vreg->reg = devm_regulator_get(dev, vreg->name);
4784 if (IS_ERR(vreg->reg)) {
4785 ret = PTR_ERR(vreg->reg);
4786 dev_err(dev, "%s: %s get failed, err=%d\n",
4787 __func__, vreg->name, ret);
4793 static int ufshcd_init_vreg(struct ufs_hba *hba)
4796 struct device *dev = hba->dev;
4797 struct ufs_vreg_info *info = &hba->vreg_info;
4802 ret = ufshcd_get_vreg(dev, info->vcc);
4806 ret = ufshcd_get_vreg(dev, info->vccq);
4810 ret = ufshcd_get_vreg(dev, info->vccq2);
4815 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
4817 struct ufs_vreg_info *info = &hba->vreg_info;
4820 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
4825 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
4829 struct ufs_clk_info *clki;
4830 struct list_head *head = &hba->clk_list_head;
4831 unsigned long flags;
4833 if (!head || list_empty(head))
4836 list_for_each_entry(clki, head, list) {
4837 if (!IS_ERR_OR_NULL(clki->clk)) {
4838 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
4841 if (on && !clki->enabled) {
4842 ret = clk_prepare_enable(clki->clk);
4844 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
4845 __func__, clki->name, ret);
4848 } else if (!on && clki->enabled) {
4849 clk_disable_unprepare(clki->clk);
4852 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
4853 clki->name, on ? "en" : "dis");
4857 ret = ufshcd_vops_setup_clocks(hba, on);
4860 list_for_each_entry(clki, head, list) {
4861 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
4862 clk_disable_unprepare(clki->clk);
4865 spin_lock_irqsave(hba->host->host_lock, flags);
4866 hba->clk_gating.state = CLKS_ON;
4867 spin_unlock_irqrestore(hba->host->host_lock, flags);
4872 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
4874 return __ufshcd_setup_clocks(hba, on, false);
4877 static int ufshcd_init_clocks(struct ufs_hba *hba)
4880 struct ufs_clk_info *clki;
4881 struct device *dev = hba->dev;
4882 struct list_head *head = &hba->clk_list_head;
4884 if (!head || list_empty(head))
4887 list_for_each_entry(clki, head, list) {
4891 clki->clk = devm_clk_get(dev, clki->name);
4892 if (IS_ERR(clki->clk)) {
4893 ret = PTR_ERR(clki->clk);
4894 dev_err(dev, "%s: %s clk get failed, %d\n",
4895 __func__, clki->name, ret);
4899 if (clki->max_freq) {
4900 ret = clk_set_rate(clki->clk, clki->max_freq);
4902 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
4903 __func__, clki->name,
4904 clki->max_freq, ret);
4907 clki->curr_freq = clki->max_freq;
4909 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
4910 clki->name, clk_get_rate(clki->clk));
4916 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
4923 err = ufshcd_vops_init(hba);
4927 err = ufshcd_vops_setup_regulators(hba, true);
4934 ufshcd_vops_exit(hba);
4937 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
4938 __func__, ufshcd_get_var_name(hba), err);
4942 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
4947 ufshcd_vops_setup_clocks(hba, false);
4949 ufshcd_vops_setup_regulators(hba, false);
4951 ufshcd_vops_exit(hba);
4954 static int ufshcd_hba_init(struct ufs_hba *hba)
4959 * Handle host controller power separately from the UFS device power
4960 * rails as it will help controlling the UFS host controller power
4961 * collapse easily which is different than UFS device power collapse.
4962 * Also, enable the host controller power before we go ahead with rest
4963 * of the initialization here.
4965 err = ufshcd_init_hba_vreg(hba);
4969 err = ufshcd_setup_hba_vreg(hba, true);
4973 err = ufshcd_init_clocks(hba);
4975 goto out_disable_hba_vreg;
4977 err = ufshcd_setup_clocks(hba, true);
4979 goto out_disable_hba_vreg;
4981 err = ufshcd_init_vreg(hba);
4983 goto out_disable_clks;
4985 err = ufshcd_setup_vreg(hba, true);
4987 goto out_disable_clks;
4989 err = ufshcd_variant_hba_init(hba);
4991 goto out_disable_vreg;
4993 hba->is_powered = true;
4997 ufshcd_setup_vreg(hba, false);
4999 ufshcd_setup_clocks(hba, false);
5000 out_disable_hba_vreg:
5001 ufshcd_setup_hba_vreg(hba, false);
5006 static void ufshcd_hba_exit(struct ufs_hba *hba)
5008 if (hba->is_powered) {
5009 ufshcd_variant_hba_exit(hba);
5010 ufshcd_setup_vreg(hba, false);
5011 ufshcd_setup_clocks(hba, false);
5012 ufshcd_setup_hba_vreg(hba, false);
5013 hba->is_powered = false;
5018 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5020 unsigned char cmd[6] = {REQUEST_SENSE,
5024 SCSI_SENSE_BUFFERSIZE,
5029 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5035 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5036 SCSI_SENSE_BUFFERSIZE, NULL,
5037 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5039 pr_err("%s: failed with err %d\n", __func__, ret);
5047 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5049 * @hba: per adapter instance
5050 * @pwr_mode: device power mode to set
5052 * Returns 0 if requested power mode is set successfully
5053 * Returns non-zero if failed to set the requested power mode
5055 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5056 enum ufs_dev_pwr_mode pwr_mode)
5058 unsigned char cmd[6] = { START_STOP };
5059 struct scsi_sense_hdr sshdr;
5060 struct scsi_device *sdp;
5061 unsigned long flags;
5064 spin_lock_irqsave(hba->host->host_lock, flags);
5065 sdp = hba->sdev_ufs_device;
5067 ret = scsi_device_get(sdp);
5068 if (!ret && !scsi_device_online(sdp)) {
5070 scsi_device_put(sdp);
5075 spin_unlock_irqrestore(hba->host->host_lock, flags);
5081 * If scsi commands fail, the scsi mid-layer schedules scsi error-
5082 * handling, which would wait for host to be resumed. Since we know
5083 * we are functional while we are here, skip host resume in error
5086 hba->host->eh_noresume = 1;
5087 if (hba->wlun_dev_clr_ua) {
5088 ret = ufshcd_send_request_sense(hba, sdp);
5091 /* Unit attention condition is cleared now */
5092 hba->wlun_dev_clr_ua = false;
5095 cmd[4] = pwr_mode << 4;
5098 * Current function would be generally called from the power management
5099 * callbacks hence set the REQ_PM flag so that it doesn't resume the
5100 * already suspended childs.
5102 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5103 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5105 sdev_printk(KERN_WARNING, sdp,
5106 "START_STOP failed for power mode: %d, result %x\n",
5108 if (driver_byte(ret) & DRIVER_SENSE)
5109 scsi_print_sense_hdr(sdp, NULL, &sshdr);
5113 hba->curr_dev_pwr_mode = pwr_mode;
5115 scsi_device_put(sdp);
5116 hba->host->eh_noresume = 0;
5120 static int ufshcd_link_state_transition(struct ufs_hba *hba,
5121 enum uic_link_state req_link_state,
5122 int check_for_bkops)
5126 if (req_link_state == hba->uic_link_state)
5129 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5130 ret = ufshcd_uic_hibern8_enter(hba);
5132 ufshcd_set_link_hibern8(hba);
5137 * If autobkops is enabled, link can't be turned off because
5138 * turning off the link would also turn off the device.
5140 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5141 (!check_for_bkops || (check_for_bkops &&
5142 !hba->auto_bkops_enabled))) {
5144 * Change controller state to "reset state" which
5145 * should also put the link in off/reset state
5147 ufshcd_hba_stop(hba, true);
5149 * TODO: Check if we need any delay to make sure that
5150 * controller is reset
5152 ufshcd_set_link_off(hba);
5159 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5162 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5165 * If UFS device and link is in OFF state, all power supplies (VCC,
5166 * VCCQ, VCCQ2) can be turned off if power on write protect is not
5167 * required. If UFS link is inactive (Hibern8 or OFF state) and device
5168 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5170 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5171 * in low power state which would save some power.
5173 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5174 !hba->dev_info.is_lu_power_on_wp) {
5175 ufshcd_setup_vreg(hba, false);
5176 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5177 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5178 if (!ufshcd_is_link_active(hba)) {
5179 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5180 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5185 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5189 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5190 !hba->dev_info.is_lu_power_on_wp) {
5191 ret = ufshcd_setup_vreg(hba, true);
5192 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5193 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5194 if (!ret && !ufshcd_is_link_active(hba)) {
5195 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5198 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5206 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5208 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5213 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5215 if (ufshcd_is_link_off(hba))
5216 ufshcd_setup_hba_vreg(hba, false);
5219 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5221 if (ufshcd_is_link_off(hba))
5222 ufshcd_setup_hba_vreg(hba, true);
5226 * ufshcd_suspend - helper function for suspend operations
5227 * @hba: per adapter instance
5228 * @pm_op: desired low power operation type
5230 * This function will try to put the UFS device and link into low power
5231 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5232 * (System PM level).
5234 * If this function is called during shutdown, it will make sure that
5235 * both UFS device and UFS link is powered off.
5237 * NOTE: UFS device & link must be active before we enter in this function.
5239 * Returns 0 for success and non-zero for failure
5241 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5244 enum ufs_pm_level pm_lvl;
5245 enum ufs_dev_pwr_mode req_dev_pwr_mode;
5246 enum uic_link_state req_link_state;
5248 hba->pm_op_in_progress = 1;
5249 if (!ufshcd_is_shutdown_pm(pm_op)) {
5250 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5251 hba->rpm_lvl : hba->spm_lvl;
5252 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5253 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5255 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5256 req_link_state = UIC_LINK_OFF_STATE;
5260 * If we can't transition into any of the low power modes
5261 * just gate the clocks.
5263 ufshcd_hold(hba, false);
5264 hba->clk_gating.is_suspended = true;
5266 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5267 req_link_state == UIC_LINK_ACTIVE_STATE) {
5271 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5272 (req_link_state == hba->uic_link_state))
5275 /* UFS device & link must be active before we enter in this function */
5276 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5281 if (ufshcd_is_runtime_pm(pm_op)) {
5282 if (ufshcd_can_autobkops_during_suspend(hba)) {
5284 * The device is idle with no requests in the queue,
5285 * allow background operations if bkops status shows
5286 * that performance might be impacted.
5288 ret = ufshcd_urgent_bkops(hba);
5292 /* make sure that auto bkops is disabled */
5293 ufshcd_disable_auto_bkops(hba);
5297 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5298 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5299 !ufshcd_is_runtime_pm(pm_op))) {
5300 /* ensure that bkops is disabled */
5301 ufshcd_disable_auto_bkops(hba);
5302 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5307 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5309 goto set_dev_active;
5311 ufshcd_vreg_set_lpm(hba);
5315 * The clock scaling needs access to controller registers. Hence, Wait
5316 * for pending clock scaling work to be done before clocks are
5319 if (ufshcd_is_clkscaling_enabled(hba)) {
5320 devfreq_suspend_device(hba->devfreq);
5321 hba->clk_scaling.window_start_t = 0;
5324 * Call vendor specific suspend callback. As these callbacks may access
5325 * vendor specific host controller register space call them before the
5326 * host clocks are ON.
5328 ret = ufshcd_vops_suspend(hba, pm_op);
5330 goto set_link_active;
5332 ret = ufshcd_vops_setup_clocks(hba, false);
5336 if (!ufshcd_is_link_active(hba))
5337 ufshcd_setup_clocks(hba, false);
5339 /* If link is active, device ref_clk can't be switched off */
5340 __ufshcd_setup_clocks(hba, false, true);
5342 hba->clk_gating.state = CLKS_OFF;
5344 * Disable the host irq as host controller as there won't be any
5345 * host controller transaction expected till resume.
5347 ufshcd_disable_irq(hba);
5348 /* Put the host controller in low power mode if possible */
5349 ufshcd_hba_vreg_set_lpm(hba);
5353 ufshcd_vops_resume(hba, pm_op);
5355 ufshcd_vreg_set_hpm(hba);
5356 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5357 ufshcd_set_link_active(hba);
5358 else if (ufshcd_is_link_off(hba))
5359 ufshcd_host_reset_and_restore(hba);
5361 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5362 ufshcd_disable_auto_bkops(hba);
5364 hba->clk_gating.is_suspended = false;
5365 ufshcd_release(hba);
5367 hba->pm_op_in_progress = 0;
5372 * ufshcd_resume - helper function for resume operations
5373 * @hba: per adapter instance
5374 * @pm_op: runtime PM or system PM
5376 * This function basically brings the UFS device, UniPro link and controller
5379 * Returns 0 for success and non-zero for failure
5381 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5384 enum uic_link_state old_link_state;
5386 hba->pm_op_in_progress = 1;
5387 old_link_state = hba->uic_link_state;
5389 ufshcd_hba_vreg_set_hpm(hba);
5390 /* Make sure clocks are enabled before accessing controller */
5391 ret = ufshcd_setup_clocks(hba, true);
5395 /* enable the host irq as host controller would be active soon */
5396 ret = ufshcd_enable_irq(hba);
5398 goto disable_irq_and_vops_clks;
5400 ret = ufshcd_vreg_set_hpm(hba);
5402 goto disable_irq_and_vops_clks;
5405 * Call vendor specific resume callback. As these callbacks may access
5406 * vendor specific host controller register space call them when the
5407 * host clocks are ON.
5409 ret = ufshcd_vops_resume(hba, pm_op);
5413 if (ufshcd_is_link_hibern8(hba)) {
5414 ret = ufshcd_uic_hibern8_exit(hba);
5416 ufshcd_set_link_active(hba);
5418 goto vendor_suspend;
5419 } else if (ufshcd_is_link_off(hba)) {
5420 ret = ufshcd_host_reset_and_restore(hba);
5422 * ufshcd_host_reset_and_restore() should have already
5423 * set the link state as active
5425 if (ret || !ufshcd_is_link_active(hba))
5426 goto vendor_suspend;
5429 if (!ufshcd_is_ufs_dev_active(hba)) {
5430 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5432 goto set_old_link_state;
5436 * If BKOPs operations are urgently needed at this moment then
5437 * keep auto-bkops enabled or else disable it.
5439 ufshcd_urgent_bkops(hba);
5440 hba->clk_gating.is_suspended = false;
5442 if (ufshcd_is_clkscaling_enabled(hba))
5443 devfreq_resume_device(hba->devfreq);
5445 /* Schedule clock gating in case of no access to UFS device yet */
5446 ufshcd_release(hba);
5450 ufshcd_link_state_transition(hba, old_link_state, 0);
5452 ufshcd_vops_suspend(hba, pm_op);
5454 ufshcd_vreg_set_lpm(hba);
5455 disable_irq_and_vops_clks:
5456 ufshcd_disable_irq(hba);
5457 ufshcd_setup_clocks(hba, false);
5459 hba->pm_op_in_progress = 0;
5464 * ufshcd_system_suspend - system suspend routine
5465 * @hba: per adapter instance
5466 * @pm_op: runtime PM or system PM
5468 * Check the description of ufshcd_suspend() function for more details.
5470 * Returns 0 for success and non-zero for failure
5472 int ufshcd_system_suspend(struct ufs_hba *hba)
5476 if (!hba || !hba->is_powered)
5479 if (pm_runtime_suspended(hba->dev)) {
5480 if (hba->rpm_lvl == hba->spm_lvl)
5482 * There is possibility that device may still be in
5483 * active state during the runtime suspend.
5485 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5486 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5490 * UFS device and/or UFS link low power states during runtime
5491 * suspend seems to be different than what is expected during
5492 * system suspend. Hence runtime resume the devic & link and
5493 * let the system suspend low power states to take effect.
5494 * TODO: If resume takes longer time, we might have optimize
5495 * it in future by not resuming everything if possible.
5497 ret = ufshcd_runtime_resume(hba);
5502 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5505 hba->is_sys_suspended = true;
5508 EXPORT_SYMBOL(ufshcd_system_suspend);
5511 * ufshcd_system_resume - system resume routine
5512 * @hba: per adapter instance
5514 * Returns 0 for success and non-zero for failure
5517 int ufshcd_system_resume(struct ufs_hba *hba)
5519 if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5521 * Let the runtime resume take care of resuming
5522 * if runtime suspended.
5526 return ufshcd_resume(hba, UFS_SYSTEM_PM);
5528 EXPORT_SYMBOL(ufshcd_system_resume);
5531 * ufshcd_runtime_suspend - runtime suspend routine
5532 * @hba: per adapter instance
5534 * Check the description of ufshcd_suspend() function for more details.
5536 * Returns 0 for success and non-zero for failure
5538 int ufshcd_runtime_suspend(struct ufs_hba *hba)
5540 if (!hba || !hba->is_powered)
5543 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
5545 EXPORT_SYMBOL(ufshcd_runtime_suspend);
5548 * ufshcd_runtime_resume - runtime resume routine
5549 * @hba: per adapter instance
5551 * This function basically brings the UFS device, UniPro link and controller
5552 * to active state. Following operations are done in this function:
5554 * 1. Turn on all the controller related clocks
5555 * 2. Bring the UniPro link out of Hibernate state
5556 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5558 * 4. If auto-bkops is enabled on the device, disable it.
5560 * So following would be the possible power state after this function return
5562 * S1: UFS device in Active state with VCC rail ON
5563 * UniPro link in Active state
5564 * All the UFS/UniPro controller clocks are ON
5566 * Returns 0 for success and non-zero for failure
5568 int ufshcd_runtime_resume(struct ufs_hba *hba)
5570 if (!hba || !hba->is_powered)
5573 return ufshcd_resume(hba, UFS_RUNTIME_PM);
5575 EXPORT_SYMBOL(ufshcd_runtime_resume);
5577 int ufshcd_runtime_idle(struct ufs_hba *hba)
5581 EXPORT_SYMBOL(ufshcd_runtime_idle);
5584 * ufshcd_shutdown - shutdown routine
5585 * @hba: per adapter instance
5587 * This function would power off both UFS device and UFS link.
5589 * Returns 0 always to allow force shutdown even in case of errors.
5591 int ufshcd_shutdown(struct ufs_hba *hba)
5595 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5598 if (pm_runtime_suspended(hba->dev)) {
5599 ret = ufshcd_runtime_resume(hba);
5604 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5607 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5608 /* allow force shutdown even in case of errors */
5611 EXPORT_SYMBOL(ufshcd_shutdown);
5614 * ufshcd_remove - de-allocate SCSI host and host memory space
5615 * data structure memory
5616 * @hba - per adapter instance
5618 void ufshcd_remove(struct ufs_hba *hba)
5620 scsi_remove_host(hba->host);
5621 /* disable interrupts */
5622 ufshcd_disable_intr(hba, hba->intr_mask);
5623 ufshcd_hba_stop(hba, true);
5625 scsi_host_put(hba->host);
5627 ufshcd_exit_clk_gating(hba);
5628 if (ufshcd_is_clkscaling_enabled(hba))
5629 devfreq_remove_device(hba->devfreq);
5630 ufshcd_hba_exit(hba);
5632 EXPORT_SYMBOL_GPL(ufshcd_remove);
5635 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
5636 * @hba: pointer to Host Bus Adapter (HBA)
5638 void ufshcd_dealloc_host(struct ufs_hba *hba)
5640 scsi_host_put(hba->host);
5642 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
5645 * ufshcd_set_dma_mask - Set dma mask based on the controller
5646 * addressing capability
5647 * @hba: per adapter instance
5649 * Returns 0 for success, non-zero for failure
5651 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
5653 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
5654 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
5657 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
5661 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
5662 * @dev: pointer to device handle
5663 * @hba_handle: driver private handle
5664 * Returns 0 on success, non-zero value on failure
5666 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
5668 struct Scsi_Host *host;
5669 struct ufs_hba *hba;
5674 "Invalid memory reference for dev is NULL\n");
5679 host = scsi_host_alloc(&ufshcd_driver_template,
5680 sizeof(struct ufs_hba));
5682 dev_err(dev, "scsi_host_alloc failed\n");
5686 hba = shost_priv(host);
5694 EXPORT_SYMBOL(ufshcd_alloc_host);
5696 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
5699 struct ufs_clk_info *clki;
5700 struct list_head *head = &hba->clk_list_head;
5702 if (!head || list_empty(head))
5705 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
5709 list_for_each_entry(clki, head, list) {
5710 if (!IS_ERR_OR_NULL(clki->clk)) {
5711 if (scale_up && clki->max_freq) {
5712 if (clki->curr_freq == clki->max_freq)
5714 ret = clk_set_rate(clki->clk, clki->max_freq);
5716 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5717 __func__, clki->name,
5718 clki->max_freq, ret);
5721 clki->curr_freq = clki->max_freq;
5723 } else if (!scale_up && clki->min_freq) {
5724 if (clki->curr_freq == clki->min_freq)
5726 ret = clk_set_rate(clki->clk, clki->min_freq);
5728 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5729 __func__, clki->name,
5730 clki->min_freq, ret);
5733 clki->curr_freq = clki->min_freq;
5736 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
5737 clki->name, clk_get_rate(clki->clk));
5740 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
5746 static int ufshcd_devfreq_target(struct device *dev,
5747 unsigned long *freq, u32 flags)
5750 struct ufs_hba *hba = dev_get_drvdata(dev);
5752 if (!ufshcd_is_clkscaling_enabled(hba))
5755 if (*freq == UINT_MAX)
5756 err = ufshcd_scale_clks(hba, true);
5757 else if (*freq == 0)
5758 err = ufshcd_scale_clks(hba, false);
5763 static int ufshcd_devfreq_get_dev_status(struct device *dev,
5764 struct devfreq_dev_status *stat)
5766 struct ufs_hba *hba = dev_get_drvdata(dev);
5767 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
5768 unsigned long flags;
5770 if (!ufshcd_is_clkscaling_enabled(hba))
5773 memset(stat, 0, sizeof(*stat));
5775 spin_lock_irqsave(hba->host->host_lock, flags);
5776 if (!scaling->window_start_t)
5779 if (scaling->is_busy_started)
5780 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
5781 scaling->busy_start_t));
5783 stat->total_time = jiffies_to_usecs((long)jiffies -
5784 (long)scaling->window_start_t);
5785 stat->busy_time = scaling->tot_busy_t;
5787 scaling->window_start_t = jiffies;
5788 scaling->tot_busy_t = 0;
5790 if (hba->outstanding_reqs) {
5791 scaling->busy_start_t = ktime_get();
5792 scaling->is_busy_started = true;
5794 scaling->busy_start_t = ktime_set(0, 0);
5795 scaling->is_busy_started = false;
5797 spin_unlock_irqrestore(hba->host->host_lock, flags);
5801 static struct devfreq_dev_profile ufs_devfreq_profile = {
5803 .target = ufshcd_devfreq_target,
5804 .get_dev_status = ufshcd_devfreq_get_dev_status,
5808 * ufshcd_init - Driver initialization routine
5809 * @hba: per-adapter instance
5810 * @mmio_base: base register address
5811 * @irq: Interrupt line of device
5812 * Returns 0 on success, non-zero value on failure
5814 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
5817 struct Scsi_Host *host = hba->host;
5818 struct device *dev = hba->dev;
5822 "Invalid memory reference for mmio_base is NULL\n");
5827 hba->mmio_base = mmio_base;
5830 err = ufshcd_hba_init(hba);
5834 /* Read capabilities registers */
5835 ufshcd_hba_capabilities(hba);
5837 /* Get UFS version supported by the controller */
5838 hba->ufs_version = ufshcd_get_ufs_version(hba);
5840 /* Get Interrupt bit mask per version */
5841 hba->intr_mask = ufshcd_get_intr_mask(hba);
5843 err = ufshcd_set_dma_mask(hba);
5845 dev_err(hba->dev, "set dma mask failed\n");
5849 /* Allocate memory for host memory space */
5850 err = ufshcd_memory_alloc(hba);
5852 dev_err(hba->dev, "Memory allocation failed\n");
5857 ufshcd_host_memory_configure(hba);
5859 host->can_queue = hba->nutrs;
5860 host->cmd_per_lun = hba->nutrs;
5861 host->max_id = UFSHCD_MAX_ID;
5862 host->max_lun = UFS_MAX_LUNS;
5863 host->max_channel = UFSHCD_MAX_CHANNEL;
5864 host->unique_id = host->host_no;
5865 host->max_cmd_len = MAX_CDB_SIZE;
5867 hba->max_pwr_info.is_valid = false;
5869 /* Initailize wait queue for task management */
5870 init_waitqueue_head(&hba->tm_wq);
5871 init_waitqueue_head(&hba->tm_tag_wq);
5873 /* Initialize work queues */
5874 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
5875 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
5877 /* Initialize UIC command mutex */
5878 mutex_init(&hba->uic_cmd_mutex);
5880 /* Initialize mutex for device management commands */
5881 mutex_init(&hba->dev_cmd.lock);
5883 /* Initialize device management tag acquire wait queue */
5884 init_waitqueue_head(&hba->dev_cmd.tag_wq);
5886 ufshcd_init_clk_gating(hba);
5889 * In order to avoid any spurious interrupt immediately after
5890 * registering UFS controller interrupt handler, clear any pending UFS
5891 * interrupt status and disable all the UFS interrupts.
5893 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
5894 REG_INTERRUPT_STATUS);
5895 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
5897 * Make sure that UFS interrupts are disabled and any pending interrupt
5898 * status is cleared before registering UFS interrupt handler.
5902 /* IRQ registration */
5903 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
5905 dev_err(hba->dev, "request irq failed\n");
5908 hba->is_irq_enabled = true;
5911 err = scsi_add_host(host, hba->dev);
5913 dev_err(hba->dev, "scsi_add_host failed\n");
5917 /* Host controller enable */
5918 err = ufshcd_hba_enable(hba);
5920 dev_err(hba->dev, "Host controller enable failed\n");
5921 goto out_remove_scsi_host;
5924 if (ufshcd_is_clkscaling_enabled(hba)) {
5925 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
5926 "simple_ondemand", NULL);
5927 if (IS_ERR(hba->devfreq)) {
5928 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
5929 PTR_ERR(hba->devfreq));
5930 goto out_remove_scsi_host;
5932 /* Suspend devfreq until the UFS device is detected */
5933 devfreq_suspend_device(hba->devfreq);
5934 hba->clk_scaling.window_start_t = 0;
5937 /* Hold auto suspend until async scan completes */
5938 pm_runtime_get_sync(dev);
5941 * The device-initialize-sequence hasn't been invoked yet.
5942 * Set the device to power-off state
5944 ufshcd_set_ufs_dev_poweroff(hba);
5946 async_schedule(ufshcd_async_scan, hba);
5950 out_remove_scsi_host:
5951 scsi_remove_host(hba->host);
5953 ufshcd_exit_clk_gating(hba);
5955 hba->is_irq_enabled = false;
5956 scsi_host_put(host);
5957 ufshcd_hba_exit(hba);
5961 EXPORT_SYMBOL_GPL(ufshcd_init);
5963 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
5964 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
5965 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
5966 MODULE_LICENSE("GPL");
5967 MODULE_VERSION(UFSHCD_DRIVER_VERSION);