2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
46 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
49 /* UIC command timeout, unit: ms */
50 #define UIC_CMD_TIMEOUT 500
52 /* NOP OUT retries waiting for NOP IN response */
53 #define NOP_OUT_RETRIES 10
54 /* Timeout after 30 msecs if NOP OUT hangs without response */
55 #define NOP_OUT_TIMEOUT 30 /* msecs */
57 /* Query request retries */
58 #define QUERY_REQ_RETRIES 10
59 /* Query request timeout */
60 #define QUERY_REQ_TIMEOUT 30 /* msec */
62 /* Task management command timeout */
63 #define TM_CMD_TIMEOUT 100 /* msecs */
65 /* maximum number of link-startup retries */
66 #define DME_LINKSTARTUP_RETRIES 3
68 /* maximum number of reset retries before giving up */
69 #define MAX_HOST_RESET_RETRIES 5
71 /* Expose the flag value from utp_upiu_query.value */
72 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
74 /* Interrupt aggregation default timeout, unit: 40us */
75 #define INT_AGGR_DEF_TO 0x02
77 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
81 _ret = ufshcd_enable_vreg(_dev, _vreg); \
83 _ret = ufshcd_disable_vreg(_dev, _vreg); \
87 static u32 ufs_query_desc_max_size[] = {
88 QUERY_DESC_DEVICE_MAX_SIZE,
89 QUERY_DESC_CONFIGURAION_MAX_SIZE,
90 QUERY_DESC_UNIT_MAX_SIZE,
91 QUERY_DESC_RFU_MAX_SIZE,
92 QUERY_DESC_INTERCONNECT_MAX_SIZE,
93 QUERY_DESC_STRING_MAX_SIZE,
94 QUERY_DESC_RFU_MAX_SIZE,
95 QUERY_DESC_GEOMETRY_MAZ_SIZE,
96 QUERY_DESC_POWER_MAX_SIZE,
97 QUERY_DESC_RFU_MAX_SIZE,
101 UFSHCD_MAX_CHANNEL = 0,
103 UFSHCD_CMD_PER_LUN = 32,
104 UFSHCD_CAN_QUEUE = 32,
111 UFSHCD_STATE_OPERATIONAL,
114 /* UFSHCD error handling flags */
116 UFSHCD_EH_IN_PROGRESS = (1 << 0),
119 /* UFSHCD UIC layer error flags */
121 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
122 UFSHCD_UIC_NL_ERROR = (1 << 1), /* Network layer error */
123 UFSHCD_UIC_TL_ERROR = (1 << 2), /* Transport Layer error */
124 UFSHCD_UIC_DME_ERROR = (1 << 3), /* DME error */
127 /* Interrupt configuration options */
134 #define ufshcd_set_eh_in_progress(h) \
135 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
136 #define ufshcd_eh_in_progress(h) \
137 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
138 #define ufshcd_clear_eh_in_progress(h) \
139 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
141 #define ufshcd_set_ufs_dev_active(h) \
142 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
143 #define ufshcd_set_ufs_dev_sleep(h) \
144 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
145 #define ufshcd_set_ufs_dev_poweroff(h) \
146 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
147 #define ufshcd_is_ufs_dev_active(h) \
148 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
149 #define ufshcd_is_ufs_dev_sleep(h) \
150 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
151 #define ufshcd_is_ufs_dev_poweroff(h) \
152 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
154 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
155 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
156 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
157 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
158 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
159 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
160 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
163 static inline enum ufs_dev_pwr_mode
164 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
166 return ufs_pm_lvl_states[lvl].dev_state;
169 static inline enum uic_link_state
170 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
172 return ufs_pm_lvl_states[lvl].link_state;
175 static void ufshcd_tmc_handler(struct ufs_hba *hba);
176 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
177 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
178 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
179 static void ufshcd_hba_exit(struct ufs_hba *hba);
180 static int ufshcd_probe_hba(struct ufs_hba *hba);
181 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
183 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
184 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
185 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
186 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
187 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
188 static irqreturn_t ufshcd_intr(int irq, void *__hba);
189 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
190 struct ufs_pa_layer_attr *desired_pwr_mode);
192 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
196 if (!hba->is_irq_enabled) {
197 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
200 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
202 hba->is_irq_enabled = true;
208 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
210 if (hba->is_irq_enabled) {
211 free_irq(hba->irq, hba);
212 hba->is_irq_enabled = false;
217 * ufshcd_wait_for_register - wait for register value to change
218 * @hba - per-adapter interface
219 * @reg - mmio register offset
220 * @mask - mask to apply to read register value
221 * @val - wait condition
222 * @interval_us - polling interval in microsecs
223 * @timeout_ms - timeout in millisecs
225 * Returns -ETIMEDOUT on error, zero on success
227 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
228 u32 val, unsigned long interval_us, unsigned long timeout_ms)
231 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
233 /* ignore bits that we don't intend to wait on */
236 while ((ufshcd_readl(hba, reg) & mask) != val) {
237 /* wakeup within 50us of expiry */
238 usleep_range(interval_us, interval_us + 50);
240 if (time_after(jiffies, timeout)) {
241 if ((ufshcd_readl(hba, reg) & mask) != val)
251 * ufshcd_get_intr_mask - Get the interrupt bit mask
252 * @hba - Pointer to adapter instance
254 * Returns interrupt bit mask per version
256 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
258 if (hba->ufs_version == UFSHCI_VERSION_10)
259 return INTERRUPT_MASK_ALL_VER_10;
261 return INTERRUPT_MASK_ALL_VER_11;
265 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
266 * @hba - Pointer to adapter instance
268 * Returns UFSHCI version supported by the controller
270 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
272 return ufshcd_readl(hba, REG_UFS_VERSION);
276 * ufshcd_is_device_present - Check if any device connected to
277 * the host controller
278 * @hba: pointer to adapter instance
280 * Returns 1 if device present, 0 if no device detected
282 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
284 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
285 DEVICE_PRESENT) ? 1 : 0;
289 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
290 * @lrb: pointer to local command reference block
292 * This function is used to get the OCS field from UTRD
293 * Returns the OCS field in the UTRD
295 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
297 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
301 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
302 * @task_req_descp: pointer to utp_task_req_desc structure
304 * This function is used to get the OCS field from UTMRD
305 * Returns the OCS field in the UTMRD
308 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
310 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
314 * ufshcd_get_tm_free_slot - get a free slot for task management request
315 * @hba: per adapter instance
316 * @free_slot: pointer to variable with available slot value
318 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
319 * Returns 0 if free slot is not available, else return 1 with tag value
322 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
331 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
332 if (tag >= hba->nutmrs)
334 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
342 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
344 clear_bit_unlock(slot, &hba->tm_slots_in_use);
348 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
349 * @hba: per adapter instance
350 * @pos: position of the bit to be cleared
352 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
354 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
358 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
359 * @reg: Register value of host controller status
361 * Returns integer, 0 on Success and positive value if failed
363 static inline int ufshcd_get_lists_status(u32 reg)
366 * The mask 0xFF is for the following HCS register bits
376 return (((reg) & (0xFF)) >> 1) ^ (0x07);
380 * ufshcd_get_uic_cmd_result - Get the UIC command result
381 * @hba: Pointer to adapter instance
383 * This function gets the result of UIC command completion
384 * Returns 0 on success, non zero value on error
386 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
388 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
389 MASK_UIC_COMMAND_RESULT;
393 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
394 * @hba: Pointer to adapter instance
396 * This function gets UIC command argument3
397 * Returns 0 on success, non zero value on error
399 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
401 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
405 * ufshcd_get_req_rsp - returns the TR response transaction type
406 * @ucd_rsp_ptr: pointer to response UPIU
409 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
411 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
415 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
416 * @ucd_rsp_ptr: pointer to response UPIU
418 * This function gets the response status and scsi_status from response UPIU
419 * Returns the response result code.
422 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
424 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
428 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
430 * @ucd_rsp_ptr: pointer to response UPIU
432 * Return the data segment length.
434 static inline unsigned int
435 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
437 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
438 MASK_RSP_UPIU_DATA_SEG_LEN;
442 * ufshcd_is_exception_event - Check if the device raised an exception event
443 * @ucd_rsp_ptr: pointer to response UPIU
445 * The function checks if the device raised an exception event indicated in
446 * the Device Information field of response UPIU.
448 * Returns true if exception is raised, false otherwise.
450 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
452 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
453 MASK_RSP_EXCEPTION_EVENT ? true : false;
457 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
458 * @hba: per adapter instance
461 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
463 ufshcd_writel(hba, INT_AGGR_ENABLE |
464 INT_AGGR_COUNTER_AND_TIMER_RESET,
465 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
469 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
470 * @hba: per adapter instance
471 * @cnt: Interrupt aggregation counter threshold
472 * @tmout: Interrupt aggregation timeout value
475 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
477 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
478 INT_AGGR_COUNTER_THLD_VAL(cnt) |
479 INT_AGGR_TIMEOUT_VAL(tmout),
480 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
484 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
485 * When run-stop registers are set to 1, it indicates the
486 * host controller that it can process the requests
487 * @hba: per adapter instance
489 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
491 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
492 REG_UTP_TASK_REQ_LIST_RUN_STOP);
493 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
494 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
498 * ufshcd_hba_start - Start controller initialization sequence
499 * @hba: per adapter instance
501 static inline void ufshcd_hba_start(struct ufs_hba *hba)
503 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
507 * ufshcd_is_hba_active - Get controller state
508 * @hba: per adapter instance
510 * Returns zero if controller is active, 1 otherwise
512 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
514 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
517 static void ufshcd_ungate_work(struct work_struct *work)
521 struct ufs_hba *hba = container_of(work, struct ufs_hba,
522 clk_gating.ungate_work);
524 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
526 spin_lock_irqsave(hba->host->host_lock, flags);
527 if (hba->clk_gating.state == CLKS_ON) {
528 spin_unlock_irqrestore(hba->host->host_lock, flags);
532 spin_unlock_irqrestore(hba->host->host_lock, flags);
533 ufshcd_setup_clocks(hba, true);
535 /* Exit from hibern8 */
536 if (ufshcd_can_hibern8_during_gating(hba)) {
537 /* Prevent gating in this path */
538 hba->clk_gating.is_suspended = true;
539 if (ufshcd_is_link_hibern8(hba)) {
540 ret = ufshcd_uic_hibern8_exit(hba);
542 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
545 ufshcd_set_link_active(hba);
547 hba->clk_gating.is_suspended = false;
550 if (ufshcd_is_clkscaling_enabled(hba))
551 devfreq_resume_device(hba->devfreq);
552 scsi_unblock_requests(hba->host);
556 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
557 * Also, exit from hibern8 mode and set the link as active.
558 * @hba: per adapter instance
559 * @async: This indicates whether caller should ungate clocks asynchronously.
561 int ufshcd_hold(struct ufs_hba *hba, bool async)
566 if (!ufshcd_is_clkgating_allowed(hba))
568 spin_lock_irqsave(hba->host->host_lock, flags);
569 hba->clk_gating.active_reqs++;
572 switch (hba->clk_gating.state) {
576 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
577 hba->clk_gating.state = CLKS_ON;
581 * If we here, it means gating work is either done or
582 * currently running. Hence, fall through to cancel gating
583 * work and to enable clocks.
586 scsi_block_requests(hba->host);
587 hba->clk_gating.state = REQ_CLKS_ON;
588 schedule_work(&hba->clk_gating.ungate_work);
590 * fall through to check if we should wait for this
591 * work to be done or not.
596 hba->clk_gating.active_reqs--;
600 spin_unlock_irqrestore(hba->host->host_lock, flags);
601 flush_work(&hba->clk_gating.ungate_work);
602 /* Make sure state is CLKS_ON before returning */
603 spin_lock_irqsave(hba->host->host_lock, flags);
606 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
607 __func__, hba->clk_gating.state);
610 spin_unlock_irqrestore(hba->host->host_lock, flags);
615 static void ufshcd_gate_work(struct work_struct *work)
617 struct ufs_hba *hba = container_of(work, struct ufs_hba,
618 clk_gating.gate_work.work);
621 spin_lock_irqsave(hba->host->host_lock, flags);
622 if (hba->clk_gating.is_suspended) {
623 hba->clk_gating.state = CLKS_ON;
627 if (hba->clk_gating.active_reqs
628 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
629 || hba->lrb_in_use || hba->outstanding_tasks
630 || hba->active_uic_cmd || hba->uic_async_done)
633 spin_unlock_irqrestore(hba->host->host_lock, flags);
635 /* put the link into hibern8 mode before turning off clocks */
636 if (ufshcd_can_hibern8_during_gating(hba)) {
637 if (ufshcd_uic_hibern8_enter(hba)) {
638 hba->clk_gating.state = CLKS_ON;
641 ufshcd_set_link_hibern8(hba);
644 if (ufshcd_is_clkscaling_enabled(hba)) {
645 devfreq_suspend_device(hba->devfreq);
646 hba->clk_scaling.window_start_t = 0;
649 if (!ufshcd_is_link_active(hba))
650 ufshcd_setup_clocks(hba, false);
652 /* If link is active, device ref_clk can't be switched off */
653 __ufshcd_setup_clocks(hba, false, true);
656 * In case you are here to cancel this work the gating state
657 * would be marked as REQ_CLKS_ON. In this case keep the state
658 * as REQ_CLKS_ON which would anyway imply that clocks are off
659 * and a request to turn them on is pending. By doing this way,
660 * we keep the state machine in tact and this would ultimately
661 * prevent from doing cancel work multiple times when there are
662 * new requests arriving before the current cancel work is done.
664 spin_lock_irqsave(hba->host->host_lock, flags);
665 if (hba->clk_gating.state == REQ_CLKS_OFF)
666 hba->clk_gating.state = CLKS_OFF;
669 spin_unlock_irqrestore(hba->host->host_lock, flags);
674 /* host lock must be held before calling this variant */
675 static void __ufshcd_release(struct ufs_hba *hba)
677 if (!ufshcd_is_clkgating_allowed(hba))
680 hba->clk_gating.active_reqs--;
682 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
683 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
684 || hba->lrb_in_use || hba->outstanding_tasks
685 || hba->active_uic_cmd || hba->uic_async_done)
688 hba->clk_gating.state = REQ_CLKS_OFF;
689 schedule_delayed_work(&hba->clk_gating.gate_work,
690 msecs_to_jiffies(hba->clk_gating.delay_ms));
693 void ufshcd_release(struct ufs_hba *hba)
697 spin_lock_irqsave(hba->host->host_lock, flags);
698 __ufshcd_release(hba);
699 spin_unlock_irqrestore(hba->host->host_lock, flags);
702 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
703 struct device_attribute *attr, char *buf)
705 struct ufs_hba *hba = dev_get_drvdata(dev);
707 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
710 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
711 struct device_attribute *attr, const char *buf, size_t count)
713 struct ufs_hba *hba = dev_get_drvdata(dev);
714 unsigned long flags, value;
716 if (kstrtoul(buf, 0, &value))
719 spin_lock_irqsave(hba->host->host_lock, flags);
720 hba->clk_gating.delay_ms = value;
721 spin_unlock_irqrestore(hba->host->host_lock, flags);
725 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
727 if (!ufshcd_is_clkgating_allowed(hba))
730 hba->clk_gating.delay_ms = 150;
731 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
732 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
734 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
735 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
736 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
737 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
738 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
739 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
740 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
743 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
745 if (!ufshcd_is_clkgating_allowed(hba))
747 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
748 cancel_work_sync(&hba->clk_gating.ungate_work);
749 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
752 /* Must be called with host lock acquired */
753 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
755 if (!ufshcd_is_clkscaling_enabled(hba))
758 if (!hba->clk_scaling.is_busy_started) {
759 hba->clk_scaling.busy_start_t = ktime_get();
760 hba->clk_scaling.is_busy_started = true;
764 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
766 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
768 if (!ufshcd_is_clkscaling_enabled(hba))
771 if (!hba->outstanding_reqs && scaling->is_busy_started) {
772 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
773 scaling->busy_start_t));
774 scaling->busy_start_t = ktime_set(0, 0);
775 scaling->is_busy_started = false;
779 * ufshcd_send_command - Send SCSI or device management commands
780 * @hba: per adapter instance
781 * @task_tag: Task tag of the command
784 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
786 ufshcd_clk_scaling_start_busy(hba);
787 __set_bit(task_tag, &hba->outstanding_reqs);
788 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
792 * ufshcd_copy_sense_data - Copy sense data in case of check condition
793 * @lrb - pointer to local reference block
795 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
798 if (lrbp->sense_buffer &&
799 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
800 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
801 memcpy(lrbp->sense_buffer,
802 lrbp->ucd_rsp_ptr->sr.sense_data,
803 min_t(int, len, SCSI_SENSE_BUFFERSIZE));
808 * ufshcd_copy_query_response() - Copy the Query Response and the data
810 * @hba: per adapter instance
811 * @lrb - pointer to local reference block
814 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
816 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
818 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
820 /* Get the descriptor */
821 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
822 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
823 GENERAL_UPIU_REQUEST_SIZE;
827 /* data segment length */
828 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
829 MASK_QUERY_DATA_SEG_LEN;
830 buf_len = be16_to_cpu(
831 hba->dev_cmd.query.request.upiu_req.length);
832 if (likely(buf_len >= resp_len)) {
833 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
836 "%s: Response size is bigger than buffer",
846 * ufshcd_hba_capabilities - Read controller capabilities
847 * @hba: per adapter instance
849 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
851 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
853 /* nutrs and nutmrs are 0 based values */
854 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
856 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
860 * ufshcd_ready_for_uic_cmd - Check if controller is ready
861 * to accept UIC commands
862 * @hba: per adapter instance
863 * Return true on success, else false
865 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
867 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
874 * ufshcd_get_upmcrs - Get the power mode change request status
875 * @hba: Pointer to adapter instance
877 * This function gets the UPMCRS field of HCS register
878 * Returns value of UPMCRS field
880 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
882 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
886 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
887 * @hba: per adapter instance
888 * @uic_cmd: UIC command
890 * Mutex must be held.
893 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
895 WARN_ON(hba->active_uic_cmd);
897 hba->active_uic_cmd = uic_cmd;
900 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
901 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
902 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
905 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
910 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
911 * @hba: per adapter instance
912 * @uic_command: UIC command
914 * Must be called with mutex held.
915 * Returns 0 only if success.
918 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
923 if (wait_for_completion_timeout(&uic_cmd->done,
924 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
925 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
929 spin_lock_irqsave(hba->host->host_lock, flags);
930 hba->active_uic_cmd = NULL;
931 spin_unlock_irqrestore(hba->host->host_lock, flags);
937 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
938 * @hba: per adapter instance
939 * @uic_cmd: UIC command
941 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
942 * with mutex held and host_lock locked.
943 * Returns 0 only if success.
946 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
948 if (!ufshcd_ready_for_uic_cmd(hba)) {
950 "Controller not ready to accept UIC commands\n");
954 init_completion(&uic_cmd->done);
956 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
962 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
963 * @hba: per adapter instance
964 * @uic_cmd: UIC command
966 * Returns 0 only if success.
969 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
974 ufshcd_hold(hba, false);
975 mutex_lock(&hba->uic_cmd_mutex);
976 ufshcd_add_delay_before_dme_cmd(hba);
978 spin_lock_irqsave(hba->host->host_lock, flags);
979 ret = __ufshcd_send_uic_cmd(hba, uic_cmd);
980 spin_unlock_irqrestore(hba->host->host_lock, flags);
982 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
984 mutex_unlock(&hba->uic_cmd_mutex);
991 * ufshcd_map_sg - Map scatter-gather list to prdt
992 * @lrbp - pointer to local reference block
994 * Returns 0 in case of success, non-zero value in case of failure
996 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
998 struct ufshcd_sg_entry *prd_table;
999 struct scatterlist *sg;
1000 struct scsi_cmnd *cmd;
1005 sg_segments = scsi_dma_map(cmd);
1006 if (sg_segments < 0)
1010 lrbp->utr_descriptor_ptr->prd_table_length =
1011 cpu_to_le16((u16) (sg_segments));
1013 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1015 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1017 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1018 prd_table[i].base_addr =
1019 cpu_to_le32(lower_32_bits(sg->dma_address));
1020 prd_table[i].upper_addr =
1021 cpu_to_le32(upper_32_bits(sg->dma_address));
1024 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1031 * ufshcd_enable_intr - enable interrupts
1032 * @hba: per adapter instance
1033 * @intrs: interrupt bits
1035 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1037 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1039 if (hba->ufs_version == UFSHCI_VERSION_10) {
1041 rw = set & INTERRUPT_MASK_RW_VER_10;
1042 set = rw | ((set ^ intrs) & intrs);
1047 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1051 * ufshcd_disable_intr - disable interrupts
1052 * @hba: per adapter instance
1053 * @intrs: interrupt bits
1055 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1057 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1059 if (hba->ufs_version == UFSHCI_VERSION_10) {
1061 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1062 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1063 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1069 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1073 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1074 * descriptor according to request
1075 * @lrbp: pointer to local reference block
1076 * @upiu_flags: flags required in the header
1077 * @cmd_dir: requests data direction
1079 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1080 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1082 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1086 if (cmd_dir == DMA_FROM_DEVICE) {
1087 data_direction = UTP_DEVICE_TO_HOST;
1088 *upiu_flags = UPIU_CMD_FLAGS_READ;
1089 } else if (cmd_dir == DMA_TO_DEVICE) {
1090 data_direction = UTP_HOST_TO_DEVICE;
1091 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1093 data_direction = UTP_NO_DATA_TRANSFER;
1094 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1097 dword_0 = data_direction | (lrbp->command_type
1098 << UPIU_COMMAND_TYPE_OFFSET);
1100 dword_0 |= UTP_REQ_DESC_INT_CMD;
1102 /* Transfer request descriptor header fields */
1103 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1106 * assigning invalid value for command status. Controller
1107 * updates OCS on command completion, with the command
1110 req_desc->header.dword_2 =
1111 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1115 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1117 * @lrbp - local reference block pointer
1118 * @upiu_flags - flags
1121 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1123 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1125 /* command descriptor fields */
1126 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1127 UPIU_TRANSACTION_COMMAND, upiu_flags,
1128 lrbp->lun, lrbp->task_tag);
1129 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1130 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1132 /* Total EHS length and Data segment length will be zero */
1133 ucd_req_ptr->header.dword_2 = 0;
1135 ucd_req_ptr->sc.exp_data_transfer_len =
1136 cpu_to_be32(lrbp->cmd->sdb.length);
1138 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd,
1139 (min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE)));
1143 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1146 * @lrbp: local reference block pointer
1147 * @upiu_flags: flags
1149 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1150 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1152 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1153 struct ufs_query *query = &hba->dev_cmd.query;
1154 u16 len = be16_to_cpu(query->request.upiu_req.length);
1155 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1157 /* Query request header */
1158 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1159 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1160 lrbp->lun, lrbp->task_tag);
1161 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1162 0, query->request.query_func, 0, 0);
1164 /* Data segment length */
1165 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1166 0, 0, len >> 8, (u8)len);
1168 /* Copy the Query Request buffer as is */
1169 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1172 /* Copy the Descriptor */
1173 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1174 memcpy(descp, query->descriptor, len);
1178 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1180 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1182 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1184 /* command descriptor fields */
1185 ucd_req_ptr->header.dword_0 =
1187 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1191 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
1192 * @hba - per adapter instance
1193 * @lrb - pointer to local reference block
1195 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1200 switch (lrbp->command_type) {
1201 case UTP_CMD_TYPE_SCSI:
1202 if (likely(lrbp->cmd)) {
1203 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1204 lrbp->cmd->sc_data_direction);
1205 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1210 case UTP_CMD_TYPE_DEV_MANAGE:
1211 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1212 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1213 ufshcd_prepare_utp_query_req_upiu(
1214 hba, lrbp, upiu_flags);
1215 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1216 ufshcd_prepare_utp_nop_upiu(lrbp);
1220 case UTP_CMD_TYPE_UFS:
1221 /* For UFS native command implementation */
1223 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1228 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1229 __func__, lrbp->command_type);
1231 } /* end of switch */
1237 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1238 * @scsi_lun: scsi LUN id
1240 * Returns UPIU LUN id
1242 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1244 if (scsi_is_wlun(scsi_lun))
1245 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1248 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1252 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1253 * @scsi_lun: UPIU W-LUN id
1255 * Returns SCSI W-LUN id
1257 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1259 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1263 * ufshcd_queuecommand - main entry point for SCSI requests
1264 * @cmd: command from SCSI Midlayer
1265 * @done: call back function
1267 * Returns 0 for success, non-zero in case of failure
1269 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1271 struct ufshcd_lrb *lrbp;
1272 struct ufs_hba *hba;
1273 unsigned long flags;
1277 hba = shost_priv(host);
1279 tag = cmd->request->tag;
1281 spin_lock_irqsave(hba->host->host_lock, flags);
1282 switch (hba->ufshcd_state) {
1283 case UFSHCD_STATE_OPERATIONAL:
1285 case UFSHCD_STATE_RESET:
1286 err = SCSI_MLQUEUE_HOST_BUSY;
1288 case UFSHCD_STATE_ERROR:
1289 set_host_byte(cmd, DID_ERROR);
1290 cmd->scsi_done(cmd);
1293 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1294 __func__, hba->ufshcd_state);
1295 set_host_byte(cmd, DID_BAD_TARGET);
1296 cmd->scsi_done(cmd);
1299 spin_unlock_irqrestore(hba->host->host_lock, flags);
1301 /* acquire the tag to make sure device cmds don't use it */
1302 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1304 * Dev manage command in progress, requeue the command.
1305 * Requeuing the command helps in cases where the request *may*
1306 * find different tag instead of waiting for dev manage command
1309 err = SCSI_MLQUEUE_HOST_BUSY;
1313 err = ufshcd_hold(hba, true);
1315 err = SCSI_MLQUEUE_HOST_BUSY;
1316 clear_bit_unlock(tag, &hba->lrb_in_use);
1319 WARN_ON(hba->clk_gating.state != CLKS_ON);
1321 lrbp = &hba->lrb[tag];
1325 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1326 lrbp->sense_buffer = cmd->sense_buffer;
1327 lrbp->task_tag = tag;
1328 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1329 lrbp->intr_cmd = false;
1330 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1332 /* form UPIU before issuing the command */
1333 ufshcd_compose_upiu(hba, lrbp);
1334 err = ufshcd_map_sg(lrbp);
1337 clear_bit_unlock(tag, &hba->lrb_in_use);
1341 /* issue command to the controller */
1342 spin_lock_irqsave(hba->host->host_lock, flags);
1343 ufshcd_send_command(hba, tag);
1345 spin_unlock_irqrestore(hba->host->host_lock, flags);
1350 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1351 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1354 lrbp->sense_bufflen = 0;
1355 lrbp->sense_buffer = NULL;
1356 lrbp->task_tag = tag;
1357 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1358 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1359 lrbp->intr_cmd = true; /* No interrupt aggregation */
1360 hba->dev_cmd.type = cmd_type;
1362 return ufshcd_compose_upiu(hba, lrbp);
1366 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1369 unsigned long flags;
1370 u32 mask = 1 << tag;
1372 /* clear outstanding transaction before retry */
1373 spin_lock_irqsave(hba->host->host_lock, flags);
1374 ufshcd_utrl_clear(hba, tag);
1375 spin_unlock_irqrestore(hba->host->host_lock, flags);
1378 * wait for for h/w to clear corresponding bit in door-bell.
1379 * max. wait is 1 sec.
1381 err = ufshcd_wait_for_register(hba,
1382 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1383 mask, ~mask, 1000, 1000);
1389 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1391 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1393 /* Get the UPIU response */
1394 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1395 UPIU_RSP_CODE_OFFSET;
1396 return query_res->response;
1400 * ufshcd_dev_cmd_completion() - handles device management command responses
1401 * @hba: per adapter instance
1402 * @lrbp: pointer to local reference block
1405 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1410 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1413 case UPIU_TRANSACTION_NOP_IN:
1414 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1416 dev_err(hba->dev, "%s: unexpected response %x\n",
1420 case UPIU_TRANSACTION_QUERY_RSP:
1421 err = ufshcd_check_query_response(hba, lrbp);
1423 err = ufshcd_copy_query_response(hba, lrbp);
1425 case UPIU_TRANSACTION_REJECT_UPIU:
1426 /* TODO: handle Reject UPIU Response */
1428 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1433 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1441 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1442 struct ufshcd_lrb *lrbp, int max_timeout)
1445 unsigned long time_left;
1446 unsigned long flags;
1448 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1449 msecs_to_jiffies(max_timeout));
1451 spin_lock_irqsave(hba->host->host_lock, flags);
1452 hba->dev_cmd.complete = NULL;
1453 if (likely(time_left)) {
1454 err = ufshcd_get_tr_ocs(lrbp);
1456 err = ufshcd_dev_cmd_completion(hba, lrbp);
1458 spin_unlock_irqrestore(hba->host->host_lock, flags);
1462 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1463 /* sucessfully cleared the command, retry if needed */
1471 * ufshcd_get_dev_cmd_tag - Get device management command tag
1472 * @hba: per-adapter instance
1473 * @tag: pointer to variable with available slot value
1475 * Get a free slot and lock it until device management command
1478 * Returns false if free slot is unavailable for locking, else
1479 * return true with tag value in @tag.
1481 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1491 tmp = ~hba->lrb_in_use;
1492 tag = find_last_bit(&tmp, hba->nutrs);
1493 if (tag >= hba->nutrs)
1495 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1503 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1505 clear_bit_unlock(tag, &hba->lrb_in_use);
1509 * ufshcd_exec_dev_cmd - API for sending device management requests
1511 * @cmd_type - specifies the type (NOP, Query...)
1512 * @timeout - time in seconds
1514 * NOTE: Since there is only one available tag for device management commands,
1515 * it is expected you hold the hba->dev_cmd.lock mutex.
1517 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1518 enum dev_cmd_type cmd_type, int timeout)
1520 struct ufshcd_lrb *lrbp;
1523 struct completion wait;
1524 unsigned long flags;
1527 * Get free slot, sleep if slots are unavailable.
1528 * Even though we use wait_event() which sleeps indefinitely,
1529 * the maximum wait time is bounded by SCSI request timeout.
1531 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1533 init_completion(&wait);
1534 lrbp = &hba->lrb[tag];
1536 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1540 hba->dev_cmd.complete = &wait;
1542 spin_lock_irqsave(hba->host->host_lock, flags);
1543 ufshcd_send_command(hba, tag);
1544 spin_unlock_irqrestore(hba->host->host_lock, flags);
1546 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1549 ufshcd_put_dev_cmd_tag(hba, tag);
1550 wake_up(&hba->dev_cmd.tag_wq);
1555 * ufshcd_init_query() - init the query response and request parameters
1556 * @hba: per-adapter instance
1557 * @request: address of the request pointer to be initialized
1558 * @response: address of the response pointer to be initialized
1559 * @opcode: operation to perform
1560 * @idn: flag idn to access
1561 * @index: LU number to access
1562 * @selector: query/flag/descriptor further identification
1564 static inline void ufshcd_init_query(struct ufs_hba *hba,
1565 struct ufs_query_req **request, struct ufs_query_res **response,
1566 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1568 *request = &hba->dev_cmd.query.request;
1569 *response = &hba->dev_cmd.query.response;
1570 memset(*request, 0, sizeof(struct ufs_query_req));
1571 memset(*response, 0, sizeof(struct ufs_query_res));
1572 (*request)->upiu_req.opcode = opcode;
1573 (*request)->upiu_req.idn = idn;
1574 (*request)->upiu_req.index = index;
1575 (*request)->upiu_req.selector = selector;
1579 * ufshcd_query_flag() - API function for sending flag query requests
1580 * hba: per-adapter instance
1581 * query_opcode: flag query to perform
1582 * idn: flag idn to access
1583 * flag_res: the flag value after the query request completes
1585 * Returns 0 for success, non-zero in case of failure
1587 static int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1588 enum flag_idn idn, bool *flag_res)
1590 struct ufs_query_req *request = NULL;
1591 struct ufs_query_res *response = NULL;
1592 int err, index = 0, selector = 0;
1596 ufshcd_hold(hba, false);
1597 mutex_lock(&hba->dev_cmd.lock);
1598 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1602 case UPIU_QUERY_OPCODE_SET_FLAG:
1603 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1604 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1605 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1607 case UPIU_QUERY_OPCODE_READ_FLAG:
1608 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1610 /* No dummy reads */
1611 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1619 "%s: Expected query flag opcode but got = %d\n",
1625 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1629 "%s: Sending flag query for idn %d failed, err = %d\n",
1630 __func__, idn, err);
1635 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1636 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1639 mutex_unlock(&hba->dev_cmd.lock);
1640 ufshcd_release(hba);
1645 * ufshcd_query_attr - API function for sending attribute requests
1646 * hba: per-adapter instance
1647 * opcode: attribute opcode
1648 * idn: attribute idn to access
1649 * index: index field
1650 * selector: selector field
1651 * attr_val: the attribute value after the query request completes
1653 * Returns 0 for success, non-zero in case of failure
1655 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1656 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1658 struct ufs_query_req *request = NULL;
1659 struct ufs_query_res *response = NULL;
1664 ufshcd_hold(hba, false);
1666 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1672 mutex_lock(&hba->dev_cmd.lock);
1673 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1677 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1678 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1679 request->upiu_req.value = cpu_to_be32(*attr_val);
1681 case UPIU_QUERY_OPCODE_READ_ATTR:
1682 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1685 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1691 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1694 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1695 __func__, opcode, idn, err);
1699 *attr_val = be32_to_cpu(response->upiu_res.value);
1702 mutex_unlock(&hba->dev_cmd.lock);
1704 ufshcd_release(hba);
1709 * ufshcd_query_descriptor - API function for sending descriptor requests
1710 * hba: per-adapter instance
1711 * opcode: attribute opcode
1712 * idn: attribute idn to access
1713 * index: index field
1714 * selector: selector field
1715 * desc_buf: the buffer that contains the descriptor
1716 * buf_len: length parameter passed to the device
1718 * Returns 0 for success, non-zero in case of failure.
1719 * The buf_len parameter will contain, on return, the length parameter
1720 * received on the response.
1722 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1723 enum query_opcode opcode, enum desc_idn idn, u8 index,
1724 u8 selector, u8 *desc_buf, int *buf_len)
1726 struct ufs_query_req *request = NULL;
1727 struct ufs_query_res *response = NULL;
1732 ufshcd_hold(hba, false);
1734 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1740 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1741 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1742 __func__, *buf_len);
1747 mutex_lock(&hba->dev_cmd.lock);
1748 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1750 hba->dev_cmd.query.descriptor = desc_buf;
1751 request->upiu_req.length = cpu_to_be16(*buf_len);
1754 case UPIU_QUERY_OPCODE_WRITE_DESC:
1755 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1757 case UPIU_QUERY_OPCODE_READ_DESC:
1758 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1762 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1768 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1771 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1772 __func__, opcode, idn, err);
1776 hba->dev_cmd.query.descriptor = NULL;
1777 *buf_len = be16_to_cpu(response->upiu_res.length);
1780 mutex_unlock(&hba->dev_cmd.lock);
1782 ufshcd_release(hba);
1787 * ufshcd_read_desc_param - read the specified descriptor parameter
1788 * @hba: Pointer to adapter instance
1789 * @desc_id: descriptor idn value
1790 * @desc_index: descriptor index
1791 * @param_offset: offset of the parameter to read
1792 * @param_read_buf: pointer to buffer where parameter would be read
1793 * @param_size: sizeof(param_read_buf)
1795 * Return 0 in case of success, non-zero otherwise
1797 static int ufshcd_read_desc_param(struct ufs_hba *hba,
1798 enum desc_idn desc_id,
1807 bool is_kmalloc = true;
1810 if (desc_id >= QUERY_DESC_IDN_MAX)
1813 buff_len = ufs_query_desc_max_size[desc_id];
1814 if ((param_offset + param_size) > buff_len)
1817 if (!param_offset && (param_size == buff_len)) {
1818 /* memory space already available to hold full descriptor */
1819 desc_buf = param_read_buf;
1822 /* allocate memory to hold full descriptor */
1823 desc_buf = kmalloc(buff_len, GFP_KERNEL);
1828 ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
1829 desc_id, desc_index, 0, desc_buf,
1832 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
1833 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
1834 ufs_query_desc_max_size[desc_id])
1835 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
1836 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
1837 __func__, desc_id, param_offset, buff_len, ret);
1845 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
1852 static inline int ufshcd_read_desc(struct ufs_hba *hba,
1853 enum desc_idn desc_id,
1858 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
1861 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
1865 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
1869 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
1870 * @hba: Pointer to adapter instance
1872 * @param_offset: offset of the parameter to read
1873 * @param_read_buf: pointer to buffer where parameter would be read
1874 * @param_size: sizeof(param_read_buf)
1876 * Return 0 in case of success, non-zero otherwise
1878 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
1880 enum unit_desc_param param_offset,
1885 * Unit descriptors are only available for general purpose LUs (LUN id
1886 * from 0 to 7) and RPMB Well known LU.
1888 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
1891 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
1892 param_offset, param_read_buf, param_size);
1896 * ufshcd_memory_alloc - allocate memory for host memory space data structures
1897 * @hba: per adapter instance
1899 * 1. Allocate DMA memory for Command Descriptor array
1900 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
1901 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
1902 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
1904 * 4. Allocate memory for local reference block(lrb).
1906 * Returns 0 for success, non-zero in case of failure
1908 static int ufshcd_memory_alloc(struct ufs_hba *hba)
1910 size_t utmrdl_size, utrdl_size, ucdl_size;
1912 /* Allocate memory for UTP command descriptors */
1913 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
1914 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
1916 &hba->ucdl_dma_addr,
1920 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
1921 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
1922 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
1923 * be aligned to 128 bytes as well
1925 if (!hba->ucdl_base_addr ||
1926 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
1928 "Command Descriptor Memory allocation failed\n");
1933 * Allocate memory for UTP Transfer descriptors
1934 * UFSHCI requires 1024 byte alignment of UTRD
1936 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
1937 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
1939 &hba->utrdl_dma_addr,
1941 if (!hba->utrdl_base_addr ||
1942 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
1944 "Transfer Descriptor Memory allocation failed\n");
1949 * Allocate memory for UTP Task Management descriptors
1950 * UFSHCI requires 1024 byte alignment of UTMRD
1952 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
1953 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
1955 &hba->utmrdl_dma_addr,
1957 if (!hba->utmrdl_base_addr ||
1958 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
1960 "Task Management Descriptor Memory allocation failed\n");
1964 /* Allocate memory for local reference block */
1965 hba->lrb = devm_kzalloc(hba->dev,
1966 hba->nutrs * sizeof(struct ufshcd_lrb),
1969 dev_err(hba->dev, "LRB Memory allocation failed\n");
1978 * ufshcd_host_memory_configure - configure local reference block with
1980 * @hba: per adapter instance
1982 * Configure Host memory space
1983 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
1985 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
1987 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
1988 * into local reference block.
1990 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
1992 struct utp_transfer_cmd_desc *cmd_descp;
1993 struct utp_transfer_req_desc *utrdlp;
1994 dma_addr_t cmd_desc_dma_addr;
1995 dma_addr_t cmd_desc_element_addr;
1996 u16 response_offset;
2001 utrdlp = hba->utrdl_base_addr;
2002 cmd_descp = hba->ucdl_base_addr;
2005 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2007 offsetof(struct utp_transfer_cmd_desc, prd_table);
2009 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2010 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2012 for (i = 0; i < hba->nutrs; i++) {
2013 /* Configure UTRD with command descriptor base address */
2014 cmd_desc_element_addr =
2015 (cmd_desc_dma_addr + (cmd_desc_size * i));
2016 utrdlp[i].command_desc_base_addr_lo =
2017 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2018 utrdlp[i].command_desc_base_addr_hi =
2019 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2021 /* Response upiu and prdt offset should be in double words */
2022 utrdlp[i].response_upiu_offset =
2023 cpu_to_le16((response_offset >> 2));
2024 utrdlp[i].prd_table_offset =
2025 cpu_to_le16((prdt_offset >> 2));
2026 utrdlp[i].response_upiu_length =
2027 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2029 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2030 hba->lrb[i].ucd_req_ptr =
2031 (struct utp_upiu_req *)(cmd_descp + i);
2032 hba->lrb[i].ucd_rsp_ptr =
2033 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2034 hba->lrb[i].ucd_prdt_ptr =
2035 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2040 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2041 * @hba: per adapter instance
2043 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2044 * in order to initialize the Unipro link startup procedure.
2045 * Once the Unipro links are up, the device connected to the controller
2048 * Returns 0 on success, non-zero value on failure
2050 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2052 struct uic_command uic_cmd = {0};
2055 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2057 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2060 "dme-link-startup: error code %d\n", ret);
2064 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2066 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2067 unsigned long min_sleep_time_us;
2069 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2073 * last_dme_cmd_tstamp will be 0 only for 1st call to
2076 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2077 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2079 unsigned long delta =
2080 (unsigned long) ktime_to_us(
2081 ktime_sub(ktime_get(),
2082 hba->last_dme_cmd_tstamp));
2084 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2086 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2088 return; /* no more delay required */
2091 /* allow sleep for extra 50us if needed */
2092 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2096 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2097 * @hba: per adapter instance
2098 * @attr_sel: uic command argument1
2099 * @attr_set: attribute set type as uic command argument2
2100 * @mib_val: setting value as uic command argument3
2101 * @peer: indicate whether peer or local
2103 * Returns 0 on success, non-zero value on failure
2105 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2106 u8 attr_set, u32 mib_val, u8 peer)
2108 struct uic_command uic_cmd = {0};
2109 static const char *const action[] = {
2113 const char *set = action[!!peer];
2116 uic_cmd.command = peer ?
2117 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2118 uic_cmd.argument1 = attr_sel;
2119 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2120 uic_cmd.argument3 = mib_val;
2122 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2124 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2125 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2129 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2132 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2133 * @hba: per adapter instance
2134 * @attr_sel: uic command argument1
2135 * @mib_val: the value of the attribute as returned by the UIC command
2136 * @peer: indicate whether peer or local
2138 * Returns 0 on success, non-zero value on failure
2140 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2141 u32 *mib_val, u8 peer)
2143 struct uic_command uic_cmd = {0};
2144 static const char *const action[] = {
2148 const char *get = action[!!peer];
2151 uic_cmd.command = peer ?
2152 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2153 uic_cmd.argument1 = attr_sel;
2155 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2157 dev_err(hba->dev, "%s: attr-id 0x%x error code %d\n",
2158 get, UIC_GET_ATTR_ID(attr_sel), ret);
2163 *mib_val = uic_cmd.argument3;
2167 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2170 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2171 * state) and waits for it to take effect.
2173 * @hba: per adapter instance
2174 * @cmd: UIC command to execute
2176 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2177 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2178 * and device UniPro link and hence it's final completion would be indicated by
2179 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2180 * addition to normal UIC command completion Status (UCCS). This function only
2181 * returns after the relevant status bits indicate the completion.
2183 * Returns 0 on success, non-zero value on failure
2185 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2187 struct completion uic_async_done;
2188 unsigned long flags;
2192 mutex_lock(&hba->uic_cmd_mutex);
2193 init_completion(&uic_async_done);
2194 ufshcd_add_delay_before_dme_cmd(hba);
2196 spin_lock_irqsave(hba->host->host_lock, flags);
2197 hba->uic_async_done = &uic_async_done;
2198 ret = __ufshcd_send_uic_cmd(hba, cmd);
2199 spin_unlock_irqrestore(hba->host->host_lock, flags);
2202 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2203 cmd->command, cmd->argument3, ret);
2206 ret = ufshcd_wait_for_uic_cmd(hba, cmd);
2209 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2210 cmd->command, cmd->argument3, ret);
2214 if (!wait_for_completion_timeout(hba->uic_async_done,
2215 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2217 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2218 cmd->command, cmd->argument3);
2223 status = ufshcd_get_upmcrs(hba);
2224 if (status != PWR_LOCAL) {
2226 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2227 cmd->command, status);
2228 ret = (status != PWR_OK) ? status : -1;
2231 spin_lock_irqsave(hba->host->host_lock, flags);
2232 hba->uic_async_done = NULL;
2233 spin_unlock_irqrestore(hba->host->host_lock, flags);
2234 mutex_unlock(&hba->uic_cmd_mutex);
2240 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2241 * using DME_SET primitives.
2242 * @hba: per adapter instance
2243 * @mode: powr mode value
2245 * Returns 0 on success, non-zero value on failure
2247 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2249 struct uic_command uic_cmd = {0};
2252 uic_cmd.command = UIC_CMD_DME_SET;
2253 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2254 uic_cmd.argument3 = mode;
2255 ufshcd_hold(hba, false);
2256 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2257 ufshcd_release(hba);
2262 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2264 struct uic_command uic_cmd = {0};
2266 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2268 return ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2271 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2273 struct uic_command uic_cmd = {0};
2276 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2277 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2279 ufshcd_set_link_off(hba);
2280 ret = ufshcd_host_reset_and_restore(hba);
2287 * ufshcd_init_pwr_info - setting the POR (power on reset)
2288 * values in hba power info
2289 * @hba: per-adapter instance
2291 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2293 hba->pwr_info.gear_rx = UFS_PWM_G1;
2294 hba->pwr_info.gear_tx = UFS_PWM_G1;
2295 hba->pwr_info.lane_rx = 1;
2296 hba->pwr_info.lane_tx = 1;
2297 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2298 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2299 hba->pwr_info.hs_rate = 0;
2303 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2304 * @hba: per-adapter instance
2306 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2308 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2310 if (hba->max_pwr_info.is_valid)
2313 pwr_info->pwr_tx = FASTAUTO_MODE;
2314 pwr_info->pwr_rx = FASTAUTO_MODE;
2315 pwr_info->hs_rate = PA_HS_MODE_B;
2317 /* Get the connected lane count */
2318 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2319 &pwr_info->lane_rx);
2320 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2321 &pwr_info->lane_tx);
2323 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2324 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2332 * First, get the maximum gears of HS speed.
2333 * If a zero value, it means there is no HSGEAR capability.
2334 * Then, get the maximum gears of PWM speed.
2336 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2337 if (!pwr_info->gear_rx) {
2338 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2339 &pwr_info->gear_rx);
2340 if (!pwr_info->gear_rx) {
2341 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2342 __func__, pwr_info->gear_rx);
2345 pwr_info->pwr_rx = SLOWAUTO_MODE;
2348 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2349 &pwr_info->gear_tx);
2350 if (!pwr_info->gear_tx) {
2351 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2352 &pwr_info->gear_tx);
2353 if (!pwr_info->gear_tx) {
2354 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2355 __func__, pwr_info->gear_tx);
2358 pwr_info->pwr_tx = SLOWAUTO_MODE;
2361 hba->max_pwr_info.is_valid = true;
2365 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2366 struct ufs_pa_layer_attr *pwr_mode)
2370 /* if already configured to the requested pwr_mode */
2371 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2372 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2373 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2374 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2375 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2376 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2377 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2378 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2383 * Configure attributes for power mode change with below.
2384 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2385 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2388 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2389 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2391 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2392 pwr_mode->pwr_rx == FAST_MODE)
2393 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2395 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2397 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2398 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2400 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2401 pwr_mode->pwr_tx == FAST_MODE)
2402 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2404 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2406 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2407 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2408 pwr_mode->pwr_rx == FAST_MODE ||
2409 pwr_mode->pwr_tx == FAST_MODE)
2410 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2413 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2414 | pwr_mode->pwr_tx);
2418 "%s: power mode change failed %d\n", __func__, ret);
2420 if (hba->vops && hba->vops->pwr_change_notify)
2421 hba->vops->pwr_change_notify(hba,
2422 POST_CHANGE, NULL, pwr_mode);
2424 memcpy(&hba->pwr_info, pwr_mode,
2425 sizeof(struct ufs_pa_layer_attr));
2432 * ufshcd_config_pwr_mode - configure a new power mode
2433 * @hba: per-adapter instance
2434 * @desired_pwr_mode: desired power configuration
2436 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2437 struct ufs_pa_layer_attr *desired_pwr_mode)
2439 struct ufs_pa_layer_attr final_params = { 0 };
2442 if (hba->vops && hba->vops->pwr_change_notify)
2443 hba->vops->pwr_change_notify(hba,
2444 PRE_CHANGE, desired_pwr_mode, &final_params);
2446 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2448 ret = ufshcd_change_power_mode(hba, &final_params);
2454 * ufshcd_complete_dev_init() - checks device readiness
2455 * hba: per-adapter instance
2457 * Set fDeviceInit flag and poll until device toggles it.
2459 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2461 int i, retries, err = 0;
2464 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2465 /* Set the fDeviceInit flag */
2466 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2467 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2468 if (!err || err == -ETIMEDOUT)
2470 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
2474 "%s setting fDeviceInit flag failed with error %d\n",
2479 /* poll for max. 100 iterations for fDeviceInit flag to clear */
2480 for (i = 0; i < 100 && !err && flag_res; i++) {
2481 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2482 err = ufshcd_query_flag(hba,
2483 UPIU_QUERY_OPCODE_READ_FLAG,
2484 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2485 if (!err || err == -ETIMEDOUT)
2487 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__,
2493 "%s reading fDeviceInit flag failed with error %d\n",
2497 "%s fDeviceInit was not cleared by the device\n",
2505 * ufshcd_make_hba_operational - Make UFS controller operational
2506 * @hba: per adapter instance
2508 * To bring UFS host controller to operational state,
2509 * 1. Enable required interrupts
2510 * 2. Configure interrupt aggregation
2511 * 3. Program UTRL and UTMRL base addres
2512 * 4. Configure run-stop-registers
2514 * Returns 0 on success, non-zero value on failure
2516 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2521 /* Enable required interrupts */
2522 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2524 /* Configure interrupt aggregation */
2525 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2527 /* Configure UTRL and UTMRL base address registers */
2528 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2529 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2530 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2531 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2532 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2533 REG_UTP_TASK_REQ_LIST_BASE_L);
2534 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2535 REG_UTP_TASK_REQ_LIST_BASE_H);
2538 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2539 * DEI, HEI bits must be 0
2541 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2542 if (!(ufshcd_get_lists_status(reg))) {
2543 ufshcd_enable_run_stop_reg(hba);
2546 "Host controller not ready to process requests");
2556 * ufshcd_hba_enable - initialize the controller
2557 * @hba: per adapter instance
2559 * The controller resets itself and controller firmware initialization
2560 * sequence kicks off. When controller is ready it will set
2561 * the Host Controller Enable bit to 1.
2563 * Returns 0 on success, non-zero value on failure
2565 static int ufshcd_hba_enable(struct ufs_hba *hba)
2570 * msleep of 1 and 5 used in this function might result in msleep(20),
2571 * but it was necessary to send the UFS FPGA to reset mode during
2572 * development and testing of this driver. msleep can be changed to
2573 * mdelay and retry count can be reduced based on the controller.
2575 if (!ufshcd_is_hba_active(hba)) {
2577 /* change controller state to "reset state" */
2578 ufshcd_hba_stop(hba);
2581 * This delay is based on the testing done with UFS host
2582 * controller FPGA. The delay can be changed based on the
2583 * host controller used.
2588 /* UniPro link is disabled at this point */
2589 ufshcd_set_link_off(hba);
2591 if (hba->vops && hba->vops->hce_enable_notify)
2592 hba->vops->hce_enable_notify(hba, PRE_CHANGE);
2594 /* start controller initialization sequence */
2595 ufshcd_hba_start(hba);
2598 * To initialize a UFS host controller HCE bit must be set to 1.
2599 * During initialization the HCE bit value changes from 1->0->1.
2600 * When the host controller completes initialization sequence
2601 * it sets the value of HCE bit to 1. The same HCE bit is read back
2602 * to check if the controller has completed initialization sequence.
2603 * So without this delay the value HCE = 1, set in the previous
2604 * instruction might be read back.
2605 * This delay can be changed based on the controller.
2609 /* wait for the host controller to complete initialization */
2611 while (ufshcd_is_hba_active(hba)) {
2616 "Controller enable failed\n");
2622 /* enable UIC related interrupts */
2623 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
2625 if (hba->vops && hba->vops->hce_enable_notify)
2626 hba->vops->hce_enable_notify(hba, POST_CHANGE);
2632 * ufshcd_link_startup - Initialize unipro link startup
2633 * @hba: per adapter instance
2635 * Returns 0 for success, non-zero in case of failure
2637 static int ufshcd_link_startup(struct ufs_hba *hba)
2640 int retries = DME_LINKSTARTUP_RETRIES;
2643 if (hba->vops && hba->vops->link_startup_notify)
2644 hba->vops->link_startup_notify(hba, PRE_CHANGE);
2646 ret = ufshcd_dme_link_startup(hba);
2648 /* check if device is detected by inter-connect layer */
2649 if (!ret && !ufshcd_is_device_present(hba)) {
2650 dev_err(hba->dev, "%s: Device not present\n", __func__);
2656 * DME link lost indication is only received when link is up,
2657 * but we can't be sure if the link is up until link startup
2658 * succeeds. So reset the local Uni-Pro and try again.
2660 if (ret && ufshcd_hba_enable(hba))
2662 } while (ret && retries--);
2665 /* failed to get the link up... retire */
2668 /* Include any host controller configuration via UIC commands */
2669 if (hba->vops && hba->vops->link_startup_notify) {
2670 ret = hba->vops->link_startup_notify(hba, POST_CHANGE);
2675 ret = ufshcd_make_hba_operational(hba);
2678 dev_err(hba->dev, "link startup failed %d\n", ret);
2683 * ufshcd_verify_dev_init() - Verify device initialization
2684 * @hba: per-adapter instance
2686 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
2687 * device Transport Protocol (UTP) layer is ready after a reset.
2688 * If the UTP layer at the device side is not initialized, it may
2689 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
2690 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
2692 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
2697 ufshcd_hold(hba, false);
2698 mutex_lock(&hba->dev_cmd.lock);
2699 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
2700 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
2703 if (!err || err == -ETIMEDOUT)
2706 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
2708 mutex_unlock(&hba->dev_cmd.lock);
2709 ufshcd_release(hba);
2712 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
2717 * ufshcd_set_queue_depth - set lun queue depth
2718 * @sdev: pointer to SCSI device
2720 * Read bLUQueueDepth value and activate scsi tagged command
2721 * queueing. For WLUN, queue depth is set to 1. For best-effort
2722 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
2723 * value that host can queue.
2725 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
2729 struct ufs_hba *hba;
2731 hba = shost_priv(sdev->host);
2733 lun_qdepth = hba->nutrs;
2734 ret = ufshcd_read_unit_desc_param(hba,
2735 ufshcd_scsi_to_upiu_lun(sdev->lun),
2736 UNIT_DESC_PARAM_LU_Q_DEPTH,
2738 sizeof(lun_qdepth));
2740 /* Some WLUN doesn't support unit descriptor */
2741 if (ret == -EOPNOTSUPP)
2743 else if (!lun_qdepth)
2744 /* eventually, we can figure out the real queue depth */
2745 lun_qdepth = hba->nutrs;
2747 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
2749 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
2750 __func__, lun_qdepth);
2751 scsi_change_queue_depth(sdev, lun_qdepth);
2755 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
2756 * @hba: per-adapter instance
2757 * @lun: UFS device lun id
2758 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
2760 * Returns 0 in case of success and b_lu_write_protect status would be returned
2761 * @b_lu_write_protect parameter.
2762 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
2763 * Returns -EINVAL in case of invalid parameters passed to this function.
2765 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
2767 u8 *b_lu_write_protect)
2771 if (!b_lu_write_protect)
2774 * According to UFS device spec, RPMB LU can't be write
2775 * protected so skip reading bLUWriteProtect parameter for
2776 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
2778 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
2781 ret = ufshcd_read_unit_desc_param(hba,
2783 UNIT_DESC_PARAM_LU_WR_PROTECT,
2785 sizeof(*b_lu_write_protect));
2790 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
2792 * @hba: per-adapter instance
2793 * @sdev: pointer to SCSI device
2796 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
2797 struct scsi_device *sdev)
2799 if (hba->dev_info.f_power_on_wp_en &&
2800 !hba->dev_info.is_lu_power_on_wp) {
2801 u8 b_lu_write_protect;
2803 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
2804 &b_lu_write_protect) &&
2805 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
2806 hba->dev_info.is_lu_power_on_wp = true;
2811 * ufshcd_slave_alloc - handle initial SCSI device configurations
2812 * @sdev: pointer to SCSI device
2816 static int ufshcd_slave_alloc(struct scsi_device *sdev)
2818 struct ufs_hba *hba;
2820 hba = shost_priv(sdev->host);
2822 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
2823 sdev->use_10_for_ms = 1;
2825 /* allow SCSI layer to restart the device in case of errors */
2826 sdev->allow_restart = 1;
2828 /* REPORT SUPPORTED OPERATION CODES is not supported */
2829 sdev->no_report_opcodes = 1;
2832 ufshcd_set_queue_depth(sdev);
2834 ufshcd_get_lu_power_on_wp_status(hba, sdev);
2840 * ufshcd_change_queue_depth - change queue depth
2841 * @sdev: pointer to SCSI device
2842 * @depth: required depth to set
2844 * Change queue depth and make sure the max. limits are not crossed.
2846 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
2848 struct ufs_hba *hba = shost_priv(sdev->host);
2850 if (depth > hba->nutrs)
2852 return scsi_change_queue_depth(sdev, depth);
2856 * ufshcd_slave_configure - adjust SCSI device configurations
2857 * @sdev: pointer to SCSI device
2859 static int ufshcd_slave_configure(struct scsi_device *sdev)
2861 struct request_queue *q = sdev->request_queue;
2863 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
2864 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
2870 * ufshcd_slave_destroy - remove SCSI device configurations
2871 * @sdev: pointer to SCSI device
2873 static void ufshcd_slave_destroy(struct scsi_device *sdev)
2875 struct ufs_hba *hba;
2877 hba = shost_priv(sdev->host);
2878 /* Drop the reference as it won't be needed anymore */
2879 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
2880 unsigned long flags;
2882 spin_lock_irqsave(hba->host->host_lock, flags);
2883 hba->sdev_ufs_device = NULL;
2884 spin_unlock_irqrestore(hba->host->host_lock, flags);
2889 * ufshcd_task_req_compl - handle task management request completion
2890 * @hba: per adapter instance
2891 * @index: index of the completed request
2892 * @resp: task management service response
2894 * Returns non-zero value on error, zero on success
2896 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
2898 struct utp_task_req_desc *task_req_descp;
2899 struct utp_upiu_task_rsp *task_rsp_upiup;
2900 unsigned long flags;
2904 spin_lock_irqsave(hba->host->host_lock, flags);
2906 /* Clear completed tasks from outstanding_tasks */
2907 __clear_bit(index, &hba->outstanding_tasks);
2909 task_req_descp = hba->utmrdl_base_addr;
2910 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
2912 if (ocs_value == OCS_SUCCESS) {
2913 task_rsp_upiup = (struct utp_upiu_task_rsp *)
2914 task_req_descp[index].task_rsp_upiu;
2915 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
2916 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
2918 *resp = (u8)task_result;
2920 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
2921 __func__, ocs_value);
2923 spin_unlock_irqrestore(hba->host->host_lock, flags);
2929 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
2930 * @lrb: pointer to local reference block of completed command
2931 * @scsi_status: SCSI command status
2933 * Returns value base on SCSI command status
2936 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
2940 switch (scsi_status) {
2941 case SAM_STAT_CHECK_CONDITION:
2942 ufshcd_copy_sense_data(lrbp);
2944 result |= DID_OK << 16 |
2945 COMMAND_COMPLETE << 8 |
2948 case SAM_STAT_TASK_SET_FULL:
2950 case SAM_STAT_TASK_ABORTED:
2951 ufshcd_copy_sense_data(lrbp);
2952 result |= scsi_status;
2955 result |= DID_ERROR << 16;
2957 } /* end of switch */
2963 * ufshcd_transfer_rsp_status - Get overall status of the response
2964 * @hba: per adapter instance
2965 * @lrb: pointer to local reference block of completed command
2967 * Returns result of the command to notify SCSI midlayer
2970 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2976 /* overall command status of utrd */
2977 ocs = ufshcd_get_tr_ocs(lrbp);
2981 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2984 case UPIU_TRANSACTION_RESPONSE:
2986 * get the response UPIU result to extract
2987 * the SCSI command status
2989 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
2992 * get the result based on SCSI status response
2993 * to notify the SCSI midlayer of the command status
2995 scsi_status = result & MASK_SCSI_STATUS;
2996 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
2998 if (ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
2999 schedule_work(&hba->eeh_work);
3001 case UPIU_TRANSACTION_REJECT_UPIU:
3002 /* TODO: handle Reject UPIU Response */
3003 result = DID_ERROR << 16;
3005 "Reject UPIU not fully implemented\n");
3008 result = DID_ERROR << 16;
3010 "Unexpected request response code = %x\n",
3016 result |= DID_ABORT << 16;
3018 case OCS_INVALID_COMMAND_STATUS:
3019 result |= DID_REQUEUE << 16;
3021 case OCS_INVALID_CMD_TABLE_ATTR:
3022 case OCS_INVALID_PRDT_ATTR:
3023 case OCS_MISMATCH_DATA_BUF_SIZE:
3024 case OCS_MISMATCH_RESP_UPIU_SIZE:
3025 case OCS_PEER_COMM_FAILURE:
3026 case OCS_FATAL_ERROR:
3028 result |= DID_ERROR << 16;
3030 "OCS error from controller = %x\n", ocs);
3032 } /* end of switch */
3038 * ufshcd_uic_cmd_compl - handle completion of uic command
3039 * @hba: per adapter instance
3040 * @intr_status: interrupt status generated by the controller
3042 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3044 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3045 hba->active_uic_cmd->argument2 |=
3046 ufshcd_get_uic_cmd_result(hba);
3047 hba->active_uic_cmd->argument3 =
3048 ufshcd_get_dme_attr_val(hba);
3049 complete(&hba->active_uic_cmd->done);
3052 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3053 complete(hba->uic_async_done);
3057 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3058 * @hba: per adapter instance
3060 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3062 struct ufshcd_lrb *lrbp;
3063 struct scsi_cmnd *cmd;
3064 unsigned long completed_reqs;
3069 /* Resetting interrupt aggregation counters first and reading the
3070 * DOOR_BELL afterward allows us to handle all the completed requests.
3071 * In order to prevent other interrupts starvation the DB is read once
3072 * after reset. The down side of this solution is the possibility of
3073 * false interrupt if device completes another request after resetting
3074 * aggregation and before reading the DB.
3076 ufshcd_reset_intr_aggr(hba);
3078 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3079 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3081 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3082 lrbp = &hba->lrb[index];
3085 result = ufshcd_transfer_rsp_status(hba, lrbp);
3086 scsi_dma_unmap(cmd);
3087 cmd->result = result;
3088 /* Mark completed command as NULL in LRB */
3090 clear_bit_unlock(index, &hba->lrb_in_use);
3091 /* Do not touch lrbp after scsi done */
3092 cmd->scsi_done(cmd);
3093 __ufshcd_release(hba);
3094 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3095 if (hba->dev_cmd.complete)
3096 complete(hba->dev_cmd.complete);
3100 /* clear corresponding bits of completed commands */
3101 hba->outstanding_reqs ^= completed_reqs;
3103 ufshcd_clk_scaling_update_busy(hba);
3105 /* we might have free'd some tags above */
3106 wake_up(&hba->dev_cmd.tag_wq);
3110 * ufshcd_disable_ee - disable exception event
3111 * @hba: per-adapter instance
3112 * @mask: exception event to disable
3114 * Disables exception event in the device so that the EVENT_ALERT
3117 * Returns zero on success, non-zero error value on failure.
3119 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3124 if (!(hba->ee_ctrl_mask & mask))
3127 val = hba->ee_ctrl_mask & ~mask;
3128 val &= 0xFFFF; /* 2 bytes */
3129 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3130 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3132 hba->ee_ctrl_mask &= ~mask;
3138 * ufshcd_enable_ee - enable exception event
3139 * @hba: per-adapter instance
3140 * @mask: exception event to enable
3142 * Enable corresponding exception event in the device to allow
3143 * device to alert host in critical scenarios.
3145 * Returns zero on success, non-zero error value on failure.
3147 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3152 if (hba->ee_ctrl_mask & mask)
3155 val = hba->ee_ctrl_mask | mask;
3156 val &= 0xFFFF; /* 2 bytes */
3157 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3158 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3160 hba->ee_ctrl_mask |= mask;
3166 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3167 * @hba: per-adapter instance
3169 * Allow device to manage background operations on its own. Enabling
3170 * this might lead to inconsistent latencies during normal data transfers
3171 * as the device is allowed to manage its own way of handling background
3174 * Returns zero on success, non-zero on failure.
3176 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3180 if (hba->auto_bkops_enabled)
3183 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3184 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3186 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3191 hba->auto_bkops_enabled = true;
3193 /* No need of URGENT_BKOPS exception from the device */
3194 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3196 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3203 * ufshcd_disable_auto_bkops - block device in doing background operations
3204 * @hba: per-adapter instance
3206 * Disabling background operations improves command response latency but
3207 * has drawback of device moving into critical state where the device is
3208 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3209 * host is idle so that BKOPS are managed effectively without any negative
3212 * Returns zero on success, non-zero on failure.
3214 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3218 if (!hba->auto_bkops_enabled)
3222 * If host assisted BKOPs is to be enabled, make sure
3223 * urgent bkops exception is allowed.
3225 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3227 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3232 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3233 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3235 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3237 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3241 hba->auto_bkops_enabled = false;
3247 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3248 * @hba: per adapter instance
3250 * After a device reset the device may toggle the BKOPS_EN flag
3251 * to default value. The s/w tracking variables should be updated
3252 * as well. Do this by forcing enable of auto bkops.
3254 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3256 hba->auto_bkops_enabled = false;
3257 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3258 ufshcd_enable_auto_bkops(hba);
3261 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3263 return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3264 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3268 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3269 * @hba: per-adapter instance
3270 * @status: bkops_status value
3272 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3273 * flag in the device to permit background operations if the device
3274 * bkops_status is greater than or equal to "status" argument passed to
3275 * this function, disable otherwise.
3277 * Returns 0 for success, non-zero in case of failure.
3279 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3280 * to know whether auto bkops is enabled or disabled after this function
3281 * returns control to it.
3283 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3284 enum bkops_status status)
3287 u32 curr_status = 0;
3289 err = ufshcd_get_bkops_status(hba, &curr_status);
3291 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3294 } else if (curr_status > BKOPS_STATUS_MAX) {
3295 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3296 __func__, curr_status);
3301 if (curr_status >= status)
3302 err = ufshcd_enable_auto_bkops(hba);
3304 err = ufshcd_disable_auto_bkops(hba);
3310 * ufshcd_urgent_bkops - handle urgent bkops exception event
3311 * @hba: per-adapter instance
3313 * Enable fBackgroundOpsEn flag in the device to permit background
3316 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3317 * and negative error value for any other failure.
3319 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3321 return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3324 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3326 return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3327 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3331 * ufshcd_exception_event_handler - handle exceptions raised by device
3332 * @work: pointer to work data
3334 * Read bExceptionEventStatus attribute from the device and handle the
3335 * exception event accordingly.
3337 static void ufshcd_exception_event_handler(struct work_struct *work)
3339 struct ufs_hba *hba;
3342 hba = container_of(work, struct ufs_hba, eeh_work);
3344 pm_runtime_get_sync(hba->dev);
3345 err = ufshcd_get_ee_status(hba, &status);
3347 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3352 status &= hba->ee_ctrl_mask;
3353 if (status & MASK_EE_URGENT_BKOPS) {
3354 err = ufshcd_urgent_bkops(hba);
3356 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3360 pm_runtime_put_sync(hba->dev);
3365 * ufshcd_err_handler - handle UFS errors that require s/w attention
3366 * @work: pointer to work structure
3368 static void ufshcd_err_handler(struct work_struct *work)
3370 struct ufs_hba *hba;
3371 unsigned long flags;
3377 hba = container_of(work, struct ufs_hba, eh_work);
3379 pm_runtime_get_sync(hba->dev);
3380 ufshcd_hold(hba, false);
3382 spin_lock_irqsave(hba->host->host_lock, flags);
3383 if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
3384 spin_unlock_irqrestore(hba->host->host_lock, flags);
3388 hba->ufshcd_state = UFSHCD_STATE_RESET;
3389 ufshcd_set_eh_in_progress(hba);
3391 /* Complete requests that have door-bell cleared by h/w */
3392 ufshcd_transfer_req_compl(hba);
3393 ufshcd_tmc_handler(hba);
3394 spin_unlock_irqrestore(hba->host->host_lock, flags);
3396 /* Clear pending transfer requests */
3397 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs)
3398 if (ufshcd_clear_cmd(hba, tag))
3399 err_xfer |= 1 << tag;
3401 /* Clear pending task management requests */
3402 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs)
3403 if (ufshcd_clear_tm_cmd(hba, tag))
3406 /* Complete the requests that are cleared by s/w */
3407 spin_lock_irqsave(hba->host->host_lock, flags);
3408 ufshcd_transfer_req_compl(hba);
3409 ufshcd_tmc_handler(hba);
3410 spin_unlock_irqrestore(hba->host->host_lock, flags);
3412 /* Fatal errors need reset */
3413 if (err_xfer || err_tm || (hba->saved_err & INT_FATAL_ERRORS) ||
3414 ((hba->saved_err & UIC_ERROR) &&
3415 (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR))) {
3416 err = ufshcd_reset_and_restore(hba);
3418 dev_err(hba->dev, "%s: reset and restore failed\n",
3420 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3423 * Inform scsi mid-layer that we did reset and allow to handle
3424 * Unit Attention properly.
3426 scsi_report_bus_reset(hba->host, 0);
3428 hba->saved_uic_err = 0;
3430 ufshcd_clear_eh_in_progress(hba);
3433 scsi_unblock_requests(hba->host);
3434 ufshcd_release(hba);
3435 pm_runtime_put_sync(hba->dev);
3439 * ufshcd_update_uic_error - check and set fatal UIC error flags.
3440 * @hba: per-adapter instance
3442 static void ufshcd_update_uic_error(struct ufs_hba *hba)
3446 /* PA_INIT_ERROR is fatal and needs UIC reset */
3447 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
3448 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
3449 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
3451 /* UIC NL/TL/DME errors needs software retry */
3452 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
3454 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
3456 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
3458 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
3460 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
3462 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
3464 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
3465 __func__, hba->uic_error);
3469 * ufshcd_check_errors - Check for errors that need s/w attention
3470 * @hba: per-adapter instance
3472 static void ufshcd_check_errors(struct ufs_hba *hba)
3474 bool queue_eh_work = false;
3476 if (hba->errors & INT_FATAL_ERRORS)
3477 queue_eh_work = true;
3479 if (hba->errors & UIC_ERROR) {
3481 ufshcd_update_uic_error(hba);
3483 queue_eh_work = true;
3486 if (queue_eh_work) {
3487 /* handle fatal errors only when link is functional */
3488 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
3489 /* block commands from scsi mid-layer */
3490 scsi_block_requests(hba->host);
3492 /* transfer error masks to sticky bits */
3493 hba->saved_err |= hba->errors;
3494 hba->saved_uic_err |= hba->uic_error;
3496 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3497 schedule_work(&hba->eh_work);
3501 * if (!queue_eh_work) -
3502 * Other errors are either non-fatal where host recovers
3503 * itself without s/w intervention or errors that will be
3504 * handled by the SCSI core layer.
3509 * ufshcd_tmc_handler - handle task management function completion
3510 * @hba: per adapter instance
3512 static void ufshcd_tmc_handler(struct ufs_hba *hba)
3516 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
3517 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
3518 wake_up(&hba->tm_wq);
3522 * ufshcd_sl_intr - Interrupt service routine
3523 * @hba: per adapter instance
3524 * @intr_status: contains interrupts generated by the controller
3526 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
3528 hba->errors = UFSHCD_ERROR_MASK & intr_status;
3530 ufshcd_check_errors(hba);
3532 if (intr_status & UFSHCD_UIC_MASK)
3533 ufshcd_uic_cmd_compl(hba, intr_status);
3535 if (intr_status & UTP_TASK_REQ_COMPL)
3536 ufshcd_tmc_handler(hba);
3538 if (intr_status & UTP_TRANSFER_REQ_COMPL)
3539 ufshcd_transfer_req_compl(hba);
3543 * ufshcd_intr - Main interrupt service routine
3545 * @__hba: pointer to adapter instance
3547 * Returns IRQ_HANDLED - If interrupt is valid
3548 * IRQ_NONE - If invalid interrupt
3550 static irqreturn_t ufshcd_intr(int irq, void *__hba)
3553 irqreturn_t retval = IRQ_NONE;
3554 struct ufs_hba *hba = __hba;
3556 spin_lock(hba->host->host_lock);
3557 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
3560 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
3561 ufshcd_sl_intr(hba, intr_status);
3562 retval = IRQ_HANDLED;
3564 spin_unlock(hba->host->host_lock);
3568 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
3571 u32 mask = 1 << tag;
3572 unsigned long flags;
3574 if (!test_bit(tag, &hba->outstanding_tasks))
3577 spin_lock_irqsave(hba->host->host_lock, flags);
3578 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
3579 spin_unlock_irqrestore(hba->host->host_lock, flags);
3581 /* poll for max. 1 sec to clear door bell register by h/w */
3582 err = ufshcd_wait_for_register(hba,
3583 REG_UTP_TASK_REQ_DOOR_BELL,
3584 mask, 0, 1000, 1000);
3590 * ufshcd_issue_tm_cmd - issues task management commands to controller
3591 * @hba: per adapter instance
3592 * @lun_id: LUN ID to which TM command is sent
3593 * @task_id: task ID to which the TM command is applicable
3594 * @tm_function: task management function opcode
3595 * @tm_response: task management service response return value
3597 * Returns non-zero value on error, zero on success.
3599 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
3600 u8 tm_function, u8 *tm_response)
3602 struct utp_task_req_desc *task_req_descp;
3603 struct utp_upiu_task_req *task_req_upiup;
3604 struct Scsi_Host *host;
3605 unsigned long flags;
3613 * Get free slot, sleep if slots are unavailable.
3614 * Even though we use wait_event() which sleeps indefinitely,
3615 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
3617 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
3618 ufshcd_hold(hba, false);
3620 spin_lock_irqsave(host->host_lock, flags);
3621 task_req_descp = hba->utmrdl_base_addr;
3622 task_req_descp += free_slot;
3624 /* Configure task request descriptor */
3625 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
3626 task_req_descp->header.dword_2 =
3627 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
3629 /* Configure task request UPIU */
3631 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
3632 task_tag = hba->nutrs + free_slot;
3633 task_req_upiup->header.dword_0 =
3634 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
3636 task_req_upiup->header.dword_1 =
3637 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
3639 * The host shall provide the same value for LUN field in the basic
3640 * header and for Input Parameter.
3642 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
3643 task_req_upiup->input_param2 = cpu_to_be32(task_id);
3645 /* send command to the controller */
3646 __set_bit(free_slot, &hba->outstanding_tasks);
3647 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
3649 spin_unlock_irqrestore(host->host_lock, flags);
3651 /* wait until the task management command is completed */
3652 err = wait_event_timeout(hba->tm_wq,
3653 test_bit(free_slot, &hba->tm_condition),
3654 msecs_to_jiffies(TM_CMD_TIMEOUT));
3656 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
3657 __func__, tm_function);
3658 if (ufshcd_clear_tm_cmd(hba, free_slot))
3659 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
3660 __func__, free_slot);
3663 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
3666 clear_bit(free_slot, &hba->tm_condition);
3667 ufshcd_put_tm_slot(hba, free_slot);
3668 wake_up(&hba->tm_tag_wq);
3670 ufshcd_release(hba);
3675 * ufshcd_eh_device_reset_handler - device reset handler registered to
3677 * @cmd: SCSI command pointer
3679 * Returns SUCCESS/FAILED
3681 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
3683 struct Scsi_Host *host;
3684 struct ufs_hba *hba;
3689 struct ufshcd_lrb *lrbp;
3690 unsigned long flags;
3692 host = cmd->device->host;
3693 hba = shost_priv(host);
3694 tag = cmd->request->tag;
3696 lrbp = &hba->lrb[tag];
3697 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
3698 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3704 /* clear the commands that were pending for corresponding LUN */
3705 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
3706 if (hba->lrb[pos].lun == lrbp->lun) {
3707 err = ufshcd_clear_cmd(hba, pos);
3712 spin_lock_irqsave(host->host_lock, flags);
3713 ufshcd_transfer_req_compl(hba);
3714 spin_unlock_irqrestore(host->host_lock, flags);
3719 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
3726 * ufshcd_abort - abort a specific command
3727 * @cmd: SCSI command pointer
3729 * Abort the pending command in device by sending UFS_ABORT_TASK task management
3730 * command, and in host controller by clearing the door-bell register. There can
3731 * be race between controller sending the command to the device while abort is
3732 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
3733 * really issued and then try to abort it.
3735 * Returns SUCCESS/FAILED
3737 static int ufshcd_abort(struct scsi_cmnd *cmd)
3739 struct Scsi_Host *host;
3740 struct ufs_hba *hba;
3741 unsigned long flags;
3746 struct ufshcd_lrb *lrbp;
3749 host = cmd->device->host;
3750 hba = shost_priv(host);
3751 tag = cmd->request->tag;
3753 ufshcd_hold(hba, false);
3754 /* If command is already aborted/completed, return SUCCESS */
3755 if (!(test_bit(tag, &hba->outstanding_reqs)))
3758 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3759 if (!(reg & (1 << tag))) {
3761 "%s: cmd was completed, but without a notifying intr, tag = %d",
3765 lrbp = &hba->lrb[tag];
3766 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
3767 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
3768 UFS_QUERY_TASK, &resp);
3769 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
3770 /* cmd pending in the device */
3772 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3774 * cmd not pending in the device, check if it is
3777 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3778 if (reg & (1 << tag)) {
3779 /* sleep for max. 200us to stabilize */
3780 usleep_range(100, 200);
3783 /* command completed already */
3787 err = resp; /* service response error */
3797 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
3798 UFS_ABORT_TASK, &resp);
3799 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3801 err = resp; /* service response error */
3805 err = ufshcd_clear_cmd(hba, tag);
3809 scsi_dma_unmap(cmd);
3811 spin_lock_irqsave(host->host_lock, flags);
3812 __clear_bit(tag, &hba->outstanding_reqs);
3813 hba->lrb[tag].cmd = NULL;
3814 spin_unlock_irqrestore(host->host_lock, flags);
3816 clear_bit_unlock(tag, &hba->lrb_in_use);
3817 wake_up(&hba->dev_cmd.tag_wq);
3823 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
3828 * This ufshcd_release() corresponds to the original scsi cmd that got
3829 * aborted here (as we won't get any IRQ for it).
3831 ufshcd_release(hba);
3836 * ufshcd_host_reset_and_restore - reset and restore host controller
3837 * @hba: per-adapter instance
3839 * Note that host controller reset may issue DME_RESET to
3840 * local and remote (device) Uni-Pro stack and the attributes
3841 * are reset to default state.
3843 * Returns zero on success, non-zero on failure
3845 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
3848 unsigned long flags;
3850 /* Reset the host controller */
3851 spin_lock_irqsave(hba->host->host_lock, flags);
3852 ufshcd_hba_stop(hba);
3853 spin_unlock_irqrestore(hba->host->host_lock, flags);
3855 err = ufshcd_hba_enable(hba);
3859 /* Establish the link again and restore the device */
3860 err = ufshcd_probe_hba(hba);
3862 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
3866 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
3872 * ufshcd_reset_and_restore - reset and re-initialize host/device
3873 * @hba: per-adapter instance
3875 * Reset and recover device, host and re-establish link. This
3876 * is helpful to recover the communication in fatal error conditions.
3878 * Returns zero on success, non-zero on failure
3880 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
3883 unsigned long flags;
3884 int retries = MAX_HOST_RESET_RETRIES;
3887 err = ufshcd_host_reset_and_restore(hba);
3888 } while (err && --retries);
3891 * After reset the door-bell might be cleared, complete
3892 * outstanding requests in s/w here.
3894 spin_lock_irqsave(hba->host->host_lock, flags);
3895 ufshcd_transfer_req_compl(hba);
3896 ufshcd_tmc_handler(hba);
3897 spin_unlock_irqrestore(hba->host->host_lock, flags);
3903 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
3904 * @cmd - SCSI command pointer
3906 * Returns SUCCESS/FAILED
3908 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
3911 unsigned long flags;
3912 struct ufs_hba *hba;
3914 hba = shost_priv(cmd->device->host);
3916 ufshcd_hold(hba, false);
3918 * Check if there is any race with fatal error handling.
3919 * If so, wait for it to complete. Even though fatal error
3920 * handling does reset and restore in some cases, don't assume
3921 * anything out of it. We are just avoiding race here.
3924 spin_lock_irqsave(hba->host->host_lock, flags);
3925 if (!(work_pending(&hba->eh_work) ||
3926 hba->ufshcd_state == UFSHCD_STATE_RESET))
3928 spin_unlock_irqrestore(hba->host->host_lock, flags);
3929 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
3930 flush_work(&hba->eh_work);
3933 hba->ufshcd_state = UFSHCD_STATE_RESET;
3934 ufshcd_set_eh_in_progress(hba);
3935 spin_unlock_irqrestore(hba->host->host_lock, flags);
3937 err = ufshcd_reset_and_restore(hba);
3939 spin_lock_irqsave(hba->host->host_lock, flags);
3942 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
3945 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3947 ufshcd_clear_eh_in_progress(hba);
3948 spin_unlock_irqrestore(hba->host->host_lock, flags);
3950 ufshcd_release(hba);
3955 * ufshcd_get_max_icc_level - calculate the ICC level
3956 * @sup_curr_uA: max. current supported by the regulator
3957 * @start_scan: row at the desc table to start scan from
3958 * @buff: power descriptor buffer
3960 * Returns calculated max ICC level for specific regulator
3962 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
3969 for (i = start_scan; i >= 0; i--) {
3970 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
3971 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
3972 ATTR_ICC_LVL_UNIT_OFFSET;
3973 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
3975 case UFSHCD_NANO_AMP:
3976 curr_uA = curr_uA / 1000;
3978 case UFSHCD_MILI_AMP:
3979 curr_uA = curr_uA * 1000;
3982 curr_uA = curr_uA * 1000 * 1000;
3984 case UFSHCD_MICRO_AMP:
3988 if (sup_curr_uA >= curr_uA)
3993 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4000 * ufshcd_calc_icc_level - calculate the max ICC level
4001 * In case regulators are not initialized we'll return 0
4002 * @hba: per-adapter instance
4003 * @desc_buf: power descriptor buffer to extract ICC levels from.
4004 * @len: length of desc_buff
4006 * Returns calculated ICC level
4008 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4009 u8 *desc_buf, int len)
4013 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4014 !hba->vreg_info.vccq2) {
4016 "%s: Regulator capability was not set, actvIccLevel=%d",
4017 __func__, icc_level);
4021 if (hba->vreg_info.vcc)
4022 icc_level = ufshcd_get_max_icc_level(
4023 hba->vreg_info.vcc->max_uA,
4024 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4025 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4027 if (hba->vreg_info.vccq)
4028 icc_level = ufshcd_get_max_icc_level(
4029 hba->vreg_info.vccq->max_uA,
4031 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4033 if (hba->vreg_info.vccq2)
4034 icc_level = ufshcd_get_max_icc_level(
4035 hba->vreg_info.vccq2->max_uA,
4037 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4042 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4045 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4046 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4048 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4051 "%s: Failed reading power descriptor.len = %d ret = %d",
4052 __func__, buff_len, ret);
4056 hba->init_prefetch_data.icc_level =
4057 ufshcd_find_max_sup_active_icc_level(hba,
4058 desc_buf, buff_len);
4059 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4060 __func__, hba->init_prefetch_data.icc_level);
4062 ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4063 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4064 &hba->init_prefetch_data.icc_level);
4068 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4069 __func__, hba->init_prefetch_data.icc_level , ret);
4074 * ufshcd_scsi_add_wlus - Adds required W-LUs
4075 * @hba: per-adapter instance
4077 * UFS device specification requires the UFS devices to support 4 well known
4079 * "REPORT_LUNS" (address: 01h)
4080 * "UFS Device" (address: 50h)
4081 * "RPMB" (address: 44h)
4082 * "BOOT" (address: 30h)
4083 * UFS device's power management needs to be controlled by "POWER CONDITION"
4084 * field of SSU (START STOP UNIT) command. But this "power condition" field
4085 * will take effect only when its sent to "UFS device" well known logical unit
4086 * hence we require the scsi_device instance to represent this logical unit in
4087 * order for the UFS host driver to send the SSU command for power management.
4089 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4090 * Block) LU so user space process can control this LU. User space may also
4091 * want to have access to BOOT LU.
4093 * This function adds scsi device instances for each of all well known LUs
4094 * (except "REPORT LUNS" LU).
4096 * Returns zero on success (all required W-LUs are added successfully),
4097 * non-zero error value on failure (if failed to add any of the required W-LU).
4099 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4102 struct scsi_device *sdev_rpmb;
4103 struct scsi_device *sdev_boot;
4105 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4106 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4107 if (IS_ERR(hba->sdev_ufs_device)) {
4108 ret = PTR_ERR(hba->sdev_ufs_device);
4109 hba->sdev_ufs_device = NULL;
4112 scsi_device_put(hba->sdev_ufs_device);
4114 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4115 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4116 if (IS_ERR(sdev_boot)) {
4117 ret = PTR_ERR(sdev_boot);
4118 goto remove_sdev_ufs_device;
4120 scsi_device_put(sdev_boot);
4122 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4123 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4124 if (IS_ERR(sdev_rpmb)) {
4125 ret = PTR_ERR(sdev_rpmb);
4126 goto remove_sdev_boot;
4128 scsi_device_put(sdev_rpmb);
4132 scsi_remove_device(sdev_boot);
4133 remove_sdev_ufs_device:
4134 scsi_remove_device(hba->sdev_ufs_device);
4140 * ufshcd_probe_hba - probe hba to detect device and initialize
4141 * @hba: per-adapter instance
4143 * Execute link-startup and verify device initialization
4145 static int ufshcd_probe_hba(struct ufs_hba *hba)
4149 ret = ufshcd_link_startup(hba);
4153 ufshcd_init_pwr_info(hba);
4155 /* UniPro link is active now */
4156 ufshcd_set_link_active(hba);
4158 ret = ufshcd_verify_dev_init(hba);
4162 ret = ufshcd_complete_dev_init(hba);
4166 /* UFS device is also active now */
4167 ufshcd_set_ufs_dev_active(hba);
4168 ufshcd_force_reset_auto_bkops(hba);
4169 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4170 hba->wlun_dev_clr_ua = true;
4172 if (ufshcd_get_max_pwr_mode(hba)) {
4174 "%s: Failed getting max supported power mode\n",
4177 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4179 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4184 * If we are in error handling context or in power management callbacks
4185 * context, no need to scan the host
4187 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4190 /* clear any previous UFS device information */
4191 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
4192 if (!ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4193 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
4194 hba->dev_info.f_power_on_wp_en = flag;
4196 if (!hba->is_init_prefetch)
4197 ufshcd_init_icc_levels(hba);
4199 /* Add required well known logical units to scsi mid layer */
4200 if (ufshcd_scsi_add_wlus(hba))
4203 scsi_scan_host(hba->host);
4204 pm_runtime_put_sync(hba->dev);
4207 if (!hba->is_init_prefetch)
4208 hba->is_init_prefetch = true;
4210 /* Resume devfreq after UFS device is detected */
4211 if (ufshcd_is_clkscaling_enabled(hba))
4212 devfreq_resume_device(hba->devfreq);
4216 * If we failed to initialize the device or the device is not
4217 * present, turn off the power/clocks etc.
4219 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4220 pm_runtime_put_sync(hba->dev);
4221 ufshcd_hba_exit(hba);
4228 * ufshcd_async_scan - asynchronous execution for probing hba
4229 * @data: data pointer to pass to this function
4230 * @cookie: cookie data
4232 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4234 struct ufs_hba *hba = (struct ufs_hba *)data;
4236 ufshcd_probe_hba(hba);
4239 static struct scsi_host_template ufshcd_driver_template = {
4240 .module = THIS_MODULE,
4242 .proc_name = UFSHCD,
4243 .queuecommand = ufshcd_queuecommand,
4244 .slave_alloc = ufshcd_slave_alloc,
4245 .slave_configure = ufshcd_slave_configure,
4246 .slave_destroy = ufshcd_slave_destroy,
4247 .change_queue_depth = ufshcd_change_queue_depth,
4248 .eh_abort_handler = ufshcd_abort,
4249 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4250 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
4252 .sg_tablesize = SG_ALL,
4253 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
4254 .can_queue = UFSHCD_CAN_QUEUE,
4255 .max_host_blocked = 1,
4257 .track_queue_depth = 1,
4260 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4268 ret = regulator_set_load(vreg->reg, ua);
4270 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4271 __func__, vreg->name, ua, ret);
4277 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
4278 struct ufs_vreg *vreg)
4280 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
4283 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
4284 struct ufs_vreg *vreg)
4286 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
4289 static int ufshcd_config_vreg(struct device *dev,
4290 struct ufs_vreg *vreg, bool on)
4293 struct regulator *reg = vreg->reg;
4294 const char *name = vreg->name;
4295 int min_uV, uA_load;
4299 if (regulator_count_voltages(reg) > 0) {
4300 min_uV = on ? vreg->min_uV : 0;
4301 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
4303 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
4304 __func__, name, ret);
4308 uA_load = on ? vreg->max_uA : 0;
4309 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
4317 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
4321 if (!vreg || vreg->enabled)
4324 ret = ufshcd_config_vreg(dev, vreg, true);
4326 ret = regulator_enable(vreg->reg);
4329 vreg->enabled = true;
4331 dev_err(dev, "%s: %s enable failed, err=%d\n",
4332 __func__, vreg->name, ret);
4337 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
4341 if (!vreg || !vreg->enabled)
4344 ret = regulator_disable(vreg->reg);
4347 /* ignore errors on applying disable config */
4348 ufshcd_config_vreg(dev, vreg, false);
4349 vreg->enabled = false;
4351 dev_err(dev, "%s: %s disable failed, err=%d\n",
4352 __func__, vreg->name, ret);
4358 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
4361 struct device *dev = hba->dev;
4362 struct ufs_vreg_info *info = &hba->vreg_info;
4367 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
4371 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
4375 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
4381 ufshcd_toggle_vreg(dev, info->vccq2, false);
4382 ufshcd_toggle_vreg(dev, info->vccq, false);
4383 ufshcd_toggle_vreg(dev, info->vcc, false);
4388 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
4390 struct ufs_vreg_info *info = &hba->vreg_info;
4393 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
4398 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
4405 vreg->reg = devm_regulator_get(dev, vreg->name);
4406 if (IS_ERR(vreg->reg)) {
4407 ret = PTR_ERR(vreg->reg);
4408 dev_err(dev, "%s: %s get failed, err=%d\n",
4409 __func__, vreg->name, ret);
4415 static int ufshcd_init_vreg(struct ufs_hba *hba)
4418 struct device *dev = hba->dev;
4419 struct ufs_vreg_info *info = &hba->vreg_info;
4424 ret = ufshcd_get_vreg(dev, info->vcc);
4428 ret = ufshcd_get_vreg(dev, info->vccq);
4432 ret = ufshcd_get_vreg(dev, info->vccq2);
4437 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
4439 struct ufs_vreg_info *info = &hba->vreg_info;
4442 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
4447 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
4451 struct ufs_clk_info *clki;
4452 struct list_head *head = &hba->clk_list_head;
4453 unsigned long flags;
4455 if (!head || list_empty(head))
4458 list_for_each_entry(clki, head, list) {
4459 if (!IS_ERR_OR_NULL(clki->clk)) {
4460 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
4463 if (on && !clki->enabled) {
4464 ret = clk_prepare_enable(clki->clk);
4466 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
4467 __func__, clki->name, ret);
4470 } else if (!on && clki->enabled) {
4471 clk_disable_unprepare(clki->clk);
4474 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
4475 clki->name, on ? "en" : "dis");
4479 if (hba->vops && hba->vops->setup_clocks)
4480 ret = hba->vops->setup_clocks(hba, on);
4483 list_for_each_entry(clki, head, list) {
4484 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
4485 clk_disable_unprepare(clki->clk);
4488 spin_lock_irqsave(hba->host->host_lock, flags);
4489 hba->clk_gating.state = CLKS_ON;
4490 spin_unlock_irqrestore(hba->host->host_lock, flags);
4495 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
4497 return __ufshcd_setup_clocks(hba, on, false);
4500 static int ufshcd_init_clocks(struct ufs_hba *hba)
4503 struct ufs_clk_info *clki;
4504 struct device *dev = hba->dev;
4505 struct list_head *head = &hba->clk_list_head;
4507 if (!head || list_empty(head))
4510 list_for_each_entry(clki, head, list) {
4514 clki->clk = devm_clk_get(dev, clki->name);
4515 if (IS_ERR(clki->clk)) {
4516 ret = PTR_ERR(clki->clk);
4517 dev_err(dev, "%s: %s clk get failed, %d\n",
4518 __func__, clki->name, ret);
4522 if (clki->max_freq) {
4523 ret = clk_set_rate(clki->clk, clki->max_freq);
4525 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
4526 __func__, clki->name,
4527 clki->max_freq, ret);
4530 clki->curr_freq = clki->max_freq;
4532 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
4533 clki->name, clk_get_rate(clki->clk));
4539 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
4546 if (hba->vops->init) {
4547 err = hba->vops->init(hba);
4552 if (hba->vops->setup_regulators) {
4553 err = hba->vops->setup_regulators(hba, true);
4561 if (hba->vops->exit)
4562 hba->vops->exit(hba);
4565 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
4566 __func__, hba->vops ? hba->vops->name : "", err);
4570 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
4575 if (hba->vops->setup_clocks)
4576 hba->vops->setup_clocks(hba, false);
4578 if (hba->vops->setup_regulators)
4579 hba->vops->setup_regulators(hba, false);
4581 if (hba->vops->exit)
4582 hba->vops->exit(hba);
4585 static int ufshcd_hba_init(struct ufs_hba *hba)
4590 * Handle host controller power separately from the UFS device power
4591 * rails as it will help controlling the UFS host controller power
4592 * collapse easily which is different than UFS device power collapse.
4593 * Also, enable the host controller power before we go ahead with rest
4594 * of the initialization here.
4596 err = ufshcd_init_hba_vreg(hba);
4600 err = ufshcd_setup_hba_vreg(hba, true);
4604 err = ufshcd_init_clocks(hba);
4606 goto out_disable_hba_vreg;
4608 err = ufshcd_setup_clocks(hba, true);
4610 goto out_disable_hba_vreg;
4612 err = ufshcd_init_vreg(hba);
4614 goto out_disable_clks;
4616 err = ufshcd_setup_vreg(hba, true);
4618 goto out_disable_clks;
4620 err = ufshcd_variant_hba_init(hba);
4622 goto out_disable_vreg;
4624 hba->is_powered = true;
4628 ufshcd_setup_vreg(hba, false);
4630 ufshcd_setup_clocks(hba, false);
4631 out_disable_hba_vreg:
4632 ufshcd_setup_hba_vreg(hba, false);
4637 static void ufshcd_hba_exit(struct ufs_hba *hba)
4639 if (hba->is_powered) {
4640 ufshcd_variant_hba_exit(hba);
4641 ufshcd_setup_vreg(hba, false);
4642 ufshcd_setup_clocks(hba, false);
4643 ufshcd_setup_hba_vreg(hba, false);
4644 hba->is_powered = false;
4649 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
4651 unsigned char cmd[6] = {REQUEST_SENSE,
4655 SCSI_SENSE_BUFFERSIZE,
4660 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
4666 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
4667 SCSI_SENSE_BUFFERSIZE, NULL,
4668 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
4670 pr_err("%s: failed with err %d\n", __func__, ret);
4678 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
4680 * @hba: per adapter instance
4681 * @pwr_mode: device power mode to set
4683 * Returns 0 if requested power mode is set successfully
4684 * Returns non-zero if failed to set the requested power mode
4686 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
4687 enum ufs_dev_pwr_mode pwr_mode)
4689 unsigned char cmd[6] = { START_STOP };
4690 struct scsi_sense_hdr sshdr;
4691 struct scsi_device *sdp;
4692 unsigned long flags;
4695 spin_lock_irqsave(hba->host->host_lock, flags);
4696 sdp = hba->sdev_ufs_device;
4698 ret = scsi_device_get(sdp);
4699 if (!ret && !scsi_device_online(sdp)) {
4701 scsi_device_put(sdp);
4706 spin_unlock_irqrestore(hba->host->host_lock, flags);
4712 * If scsi commands fail, the scsi mid-layer schedules scsi error-
4713 * handling, which would wait for host to be resumed. Since we know
4714 * we are functional while we are here, skip host resume in error
4717 hba->host->eh_noresume = 1;
4718 if (hba->wlun_dev_clr_ua) {
4719 ret = ufshcd_send_request_sense(hba, sdp);
4722 /* Unit attention condition is cleared now */
4723 hba->wlun_dev_clr_ua = false;
4726 cmd[4] = pwr_mode << 4;
4729 * Current function would be generally called from the power management
4730 * callbacks hence set the REQ_PM flag so that it doesn't resume the
4731 * already suspended childs.
4733 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
4734 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
4736 sdev_printk(KERN_WARNING, sdp,
4737 "START_STOP failed for power mode: %d, result %x\n",
4739 if (driver_byte(ret) & DRIVER_SENSE)
4740 scsi_print_sense_hdr(sdp, NULL, &sshdr);
4744 hba->curr_dev_pwr_mode = pwr_mode;
4746 scsi_device_put(sdp);
4747 hba->host->eh_noresume = 0;
4751 static int ufshcd_link_state_transition(struct ufs_hba *hba,
4752 enum uic_link_state req_link_state,
4753 int check_for_bkops)
4757 if (req_link_state == hba->uic_link_state)
4760 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
4761 ret = ufshcd_uic_hibern8_enter(hba);
4763 ufshcd_set_link_hibern8(hba);
4768 * If autobkops is enabled, link can't be turned off because
4769 * turning off the link would also turn off the device.
4771 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
4772 (!check_for_bkops || (check_for_bkops &&
4773 !hba->auto_bkops_enabled))) {
4775 * Change controller state to "reset state" which
4776 * should also put the link in off/reset state
4778 ufshcd_hba_stop(hba);
4780 * TODO: Check if we need any delay to make sure that
4781 * controller is reset
4783 ufshcd_set_link_off(hba);
4790 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
4793 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
4796 * If UFS device and link is in OFF state, all power supplies (VCC,
4797 * VCCQ, VCCQ2) can be turned off if power on write protect is not
4798 * required. If UFS link is inactive (Hibern8 or OFF state) and device
4799 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
4801 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
4802 * in low power state which would save some power.
4804 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
4805 !hba->dev_info.is_lu_power_on_wp) {
4806 ufshcd_setup_vreg(hba, false);
4807 } else if (!ufshcd_is_ufs_dev_active(hba)) {
4808 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
4809 if (!ufshcd_is_link_active(hba)) {
4810 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
4811 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
4816 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
4820 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
4821 !hba->dev_info.is_lu_power_on_wp) {
4822 ret = ufshcd_setup_vreg(hba, true);
4823 } else if (!ufshcd_is_ufs_dev_active(hba)) {
4824 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
4825 if (!ret && !ufshcd_is_link_active(hba)) {
4826 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
4829 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
4837 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
4839 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
4844 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
4846 if (ufshcd_is_link_off(hba))
4847 ufshcd_setup_hba_vreg(hba, false);
4850 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
4852 if (ufshcd_is_link_off(hba))
4853 ufshcd_setup_hba_vreg(hba, true);
4857 * ufshcd_suspend - helper function for suspend operations
4858 * @hba: per adapter instance
4859 * @pm_op: desired low power operation type
4861 * This function will try to put the UFS device and link into low power
4862 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
4863 * (System PM level).
4865 * If this function is called during shutdown, it will make sure that
4866 * both UFS device and UFS link is powered off.
4868 * NOTE: UFS device & link must be active before we enter in this function.
4870 * Returns 0 for success and non-zero for failure
4872 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
4875 enum ufs_pm_level pm_lvl;
4876 enum ufs_dev_pwr_mode req_dev_pwr_mode;
4877 enum uic_link_state req_link_state;
4879 hba->pm_op_in_progress = 1;
4880 if (!ufshcd_is_shutdown_pm(pm_op)) {
4881 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
4882 hba->rpm_lvl : hba->spm_lvl;
4883 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
4884 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
4886 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
4887 req_link_state = UIC_LINK_OFF_STATE;
4891 * If we can't transition into any of the low power modes
4892 * just gate the clocks.
4894 ufshcd_hold(hba, false);
4895 hba->clk_gating.is_suspended = true;
4897 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
4898 req_link_state == UIC_LINK_ACTIVE_STATE) {
4902 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
4903 (req_link_state == hba->uic_link_state))
4906 /* UFS device & link must be active before we enter in this function */
4907 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
4912 if (ufshcd_is_runtime_pm(pm_op)) {
4913 if (ufshcd_can_autobkops_during_suspend(hba)) {
4915 * The device is idle with no requests in the queue,
4916 * allow background operations if bkops status shows
4917 * that performance might be impacted.
4919 ret = ufshcd_urgent_bkops(hba);
4923 /* make sure that auto bkops is disabled */
4924 ufshcd_disable_auto_bkops(hba);
4928 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
4929 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
4930 !ufshcd_is_runtime_pm(pm_op))) {
4931 /* ensure that bkops is disabled */
4932 ufshcd_disable_auto_bkops(hba);
4933 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
4938 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
4940 goto set_dev_active;
4942 ufshcd_vreg_set_lpm(hba);
4946 * The clock scaling needs access to controller registers. Hence, Wait
4947 * for pending clock scaling work to be done before clocks are
4950 if (ufshcd_is_clkscaling_enabled(hba)) {
4951 devfreq_suspend_device(hba->devfreq);
4952 hba->clk_scaling.window_start_t = 0;
4955 * Call vendor specific suspend callback. As these callbacks may access
4956 * vendor specific host controller register space call them before the
4957 * host clocks are ON.
4959 if (hba->vops && hba->vops->suspend) {
4960 ret = hba->vops->suspend(hba, pm_op);
4962 goto set_link_active;
4965 if (hba->vops && hba->vops->setup_clocks) {
4966 ret = hba->vops->setup_clocks(hba, false);
4971 if (!ufshcd_is_link_active(hba))
4972 ufshcd_setup_clocks(hba, false);
4974 /* If link is active, device ref_clk can't be switched off */
4975 __ufshcd_setup_clocks(hba, false, true);
4977 hba->clk_gating.state = CLKS_OFF;
4979 * Disable the host irq as host controller as there won't be any
4980 * host controller trasanction expected till resume.
4982 ufshcd_disable_irq(hba);
4983 /* Put the host controller in low power mode if possible */
4984 ufshcd_hba_vreg_set_lpm(hba);
4988 if (hba->vops && hba->vops->resume)
4989 hba->vops->resume(hba, pm_op);
4991 ufshcd_vreg_set_hpm(hba);
4992 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
4993 ufshcd_set_link_active(hba);
4994 else if (ufshcd_is_link_off(hba))
4995 ufshcd_host_reset_and_restore(hba);
4997 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
4998 ufshcd_disable_auto_bkops(hba);
5000 hba->clk_gating.is_suspended = false;
5001 ufshcd_release(hba);
5003 hba->pm_op_in_progress = 0;
5008 * ufshcd_resume - helper function for resume operations
5009 * @hba: per adapter instance
5010 * @pm_op: runtime PM or system PM
5012 * This function basically brings the UFS device, UniPro link and controller
5015 * Returns 0 for success and non-zero for failure
5017 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5020 enum uic_link_state old_link_state;
5022 hba->pm_op_in_progress = 1;
5023 old_link_state = hba->uic_link_state;
5025 ufshcd_hba_vreg_set_hpm(hba);
5026 /* Make sure clocks are enabled before accessing controller */
5027 ret = ufshcd_setup_clocks(hba, true);
5031 /* enable the host irq as host controller would be active soon */
5032 ret = ufshcd_enable_irq(hba);
5034 goto disable_irq_and_vops_clks;
5036 ret = ufshcd_vreg_set_hpm(hba);
5038 goto disable_irq_and_vops_clks;
5041 * Call vendor specific resume callback. As these callbacks may access
5042 * vendor specific host controller register space call them when the
5043 * host clocks are ON.
5045 if (hba->vops && hba->vops->resume) {
5046 ret = hba->vops->resume(hba, pm_op);
5051 if (ufshcd_is_link_hibern8(hba)) {
5052 ret = ufshcd_uic_hibern8_exit(hba);
5054 ufshcd_set_link_active(hba);
5056 goto vendor_suspend;
5057 } else if (ufshcd_is_link_off(hba)) {
5058 ret = ufshcd_host_reset_and_restore(hba);
5060 * ufshcd_host_reset_and_restore() should have already
5061 * set the link state as active
5063 if (ret || !ufshcd_is_link_active(hba))
5064 goto vendor_suspend;
5067 if (!ufshcd_is_ufs_dev_active(hba)) {
5068 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5070 goto set_old_link_state;
5074 * If BKOPs operations are urgently needed at this moment then
5075 * keep auto-bkops enabled or else disable it.
5077 ufshcd_urgent_bkops(hba);
5078 hba->clk_gating.is_suspended = false;
5080 if (ufshcd_is_clkscaling_enabled(hba))
5081 devfreq_resume_device(hba->devfreq);
5083 /* Schedule clock gating in case of no access to UFS device yet */
5084 ufshcd_release(hba);
5088 ufshcd_link_state_transition(hba, old_link_state, 0);
5090 if (hba->vops && hba->vops->suspend)
5091 hba->vops->suspend(hba, pm_op);
5093 ufshcd_vreg_set_lpm(hba);
5094 disable_irq_and_vops_clks:
5095 ufshcd_disable_irq(hba);
5096 ufshcd_setup_clocks(hba, false);
5098 hba->pm_op_in_progress = 0;
5103 * ufshcd_system_suspend - system suspend routine
5104 * @hba: per adapter instance
5105 * @pm_op: runtime PM or system PM
5107 * Check the description of ufshcd_suspend() function for more details.
5109 * Returns 0 for success and non-zero for failure
5111 int ufshcd_system_suspend(struct ufs_hba *hba)
5115 if (!hba || !hba->is_powered)
5118 if (pm_runtime_suspended(hba->dev)) {
5119 if (hba->rpm_lvl == hba->spm_lvl)
5121 * There is possibility that device may still be in
5122 * active state during the runtime suspend.
5124 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5125 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5129 * UFS device and/or UFS link low power states during runtime
5130 * suspend seems to be different than what is expected during
5131 * system suspend. Hence runtime resume the devic & link and
5132 * let the system suspend low power states to take effect.
5133 * TODO: If resume takes longer time, we might have optimize
5134 * it in future by not resuming everything if possible.
5136 ret = ufshcd_runtime_resume(hba);
5141 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5144 hba->is_sys_suspended = true;
5147 EXPORT_SYMBOL(ufshcd_system_suspend);
5150 * ufshcd_system_resume - system resume routine
5151 * @hba: per adapter instance
5153 * Returns 0 for success and non-zero for failure
5156 int ufshcd_system_resume(struct ufs_hba *hba)
5158 if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5160 * Let the runtime resume take care of resuming
5161 * if runtime suspended.
5165 return ufshcd_resume(hba, UFS_SYSTEM_PM);
5167 EXPORT_SYMBOL(ufshcd_system_resume);
5170 * ufshcd_runtime_suspend - runtime suspend routine
5171 * @hba: per adapter instance
5173 * Check the description of ufshcd_suspend() function for more details.
5175 * Returns 0 for success and non-zero for failure
5177 int ufshcd_runtime_suspend(struct ufs_hba *hba)
5179 if (!hba || !hba->is_powered)
5182 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
5184 EXPORT_SYMBOL(ufshcd_runtime_suspend);
5187 * ufshcd_runtime_resume - runtime resume routine
5188 * @hba: per adapter instance
5190 * This function basically brings the UFS device, UniPro link and controller
5191 * to active state. Following operations are done in this function:
5193 * 1. Turn on all the controller related clocks
5194 * 2. Bring the UniPro link out of Hibernate state
5195 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5197 * 4. If auto-bkops is enabled on the device, disable it.
5199 * So following would be the possible power state after this function return
5201 * S1: UFS device in Active state with VCC rail ON
5202 * UniPro link in Active state
5203 * All the UFS/UniPro controller clocks are ON
5205 * Returns 0 for success and non-zero for failure
5207 int ufshcd_runtime_resume(struct ufs_hba *hba)
5209 if (!hba || !hba->is_powered)
5212 return ufshcd_resume(hba, UFS_RUNTIME_PM);
5214 EXPORT_SYMBOL(ufshcd_runtime_resume);
5216 int ufshcd_runtime_idle(struct ufs_hba *hba)
5220 EXPORT_SYMBOL(ufshcd_runtime_idle);
5223 * ufshcd_shutdown - shutdown routine
5224 * @hba: per adapter instance
5226 * This function would power off both UFS device and UFS link.
5228 * Returns 0 always to allow force shutdown even in case of errors.
5230 int ufshcd_shutdown(struct ufs_hba *hba)
5234 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5237 if (pm_runtime_suspended(hba->dev)) {
5238 ret = ufshcd_runtime_resume(hba);
5243 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5246 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5247 /* allow force shutdown even in case of errors */
5250 EXPORT_SYMBOL(ufshcd_shutdown);
5253 * ufshcd_remove - de-allocate SCSI host and host memory space
5254 * data structure memory
5255 * @hba - per adapter instance
5257 void ufshcd_remove(struct ufs_hba *hba)
5259 scsi_remove_host(hba->host);
5260 /* disable interrupts */
5261 ufshcd_disable_intr(hba, hba->intr_mask);
5262 ufshcd_hba_stop(hba);
5264 scsi_host_put(hba->host);
5266 ufshcd_exit_clk_gating(hba);
5267 if (ufshcd_is_clkscaling_enabled(hba))
5268 devfreq_remove_device(hba->devfreq);
5269 ufshcd_hba_exit(hba);
5271 EXPORT_SYMBOL_GPL(ufshcd_remove);
5274 * ufshcd_set_dma_mask - Set dma mask based on the controller
5275 * addressing capability
5276 * @hba: per adapter instance
5278 * Returns 0 for success, non-zero for failure
5280 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
5282 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
5283 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
5286 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
5290 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
5291 * @dev: pointer to device handle
5292 * @hba_handle: driver private handle
5293 * Returns 0 on success, non-zero value on failure
5295 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
5297 struct Scsi_Host *host;
5298 struct ufs_hba *hba;
5303 "Invalid memory reference for dev is NULL\n");
5308 host = scsi_host_alloc(&ufshcd_driver_template,
5309 sizeof(struct ufs_hba));
5311 dev_err(dev, "scsi_host_alloc failed\n");
5315 hba = shost_priv(host);
5323 EXPORT_SYMBOL(ufshcd_alloc_host);
5325 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
5328 struct ufs_clk_info *clki;
5329 struct list_head *head = &hba->clk_list_head;
5331 if (!head || list_empty(head))
5334 list_for_each_entry(clki, head, list) {
5335 if (!IS_ERR_OR_NULL(clki->clk)) {
5336 if (scale_up && clki->max_freq) {
5337 if (clki->curr_freq == clki->max_freq)
5339 ret = clk_set_rate(clki->clk, clki->max_freq);
5341 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5342 __func__, clki->name,
5343 clki->max_freq, ret);
5346 clki->curr_freq = clki->max_freq;
5348 } else if (!scale_up && clki->min_freq) {
5349 if (clki->curr_freq == clki->min_freq)
5351 ret = clk_set_rate(clki->clk, clki->min_freq);
5353 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5354 __func__, clki->name,
5355 clki->min_freq, ret);
5358 clki->curr_freq = clki->min_freq;
5361 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
5362 clki->name, clk_get_rate(clki->clk));
5364 if (hba->vops->clk_scale_notify)
5365 hba->vops->clk_scale_notify(hba);
5370 static int ufshcd_devfreq_target(struct device *dev,
5371 unsigned long *freq, u32 flags)
5374 struct ufs_hba *hba = dev_get_drvdata(dev);
5376 if (!ufshcd_is_clkscaling_enabled(hba))
5379 if (*freq == UINT_MAX)
5380 err = ufshcd_scale_clks(hba, true);
5381 else if (*freq == 0)
5382 err = ufshcd_scale_clks(hba, false);
5387 static int ufshcd_devfreq_get_dev_status(struct device *dev,
5388 struct devfreq_dev_status *stat)
5390 struct ufs_hba *hba = dev_get_drvdata(dev);
5391 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
5392 unsigned long flags;
5394 if (!ufshcd_is_clkscaling_enabled(hba))
5397 memset(stat, 0, sizeof(*stat));
5399 spin_lock_irqsave(hba->host->host_lock, flags);
5400 if (!scaling->window_start_t)
5403 if (scaling->is_busy_started)
5404 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
5405 scaling->busy_start_t));
5407 stat->total_time = jiffies_to_usecs((long)jiffies -
5408 (long)scaling->window_start_t);
5409 stat->busy_time = scaling->tot_busy_t;
5411 scaling->window_start_t = jiffies;
5412 scaling->tot_busy_t = 0;
5414 if (hba->outstanding_reqs) {
5415 scaling->busy_start_t = ktime_get();
5416 scaling->is_busy_started = true;
5418 scaling->busy_start_t = ktime_set(0, 0);
5419 scaling->is_busy_started = false;
5421 spin_unlock_irqrestore(hba->host->host_lock, flags);
5425 static struct devfreq_dev_profile ufs_devfreq_profile = {
5427 .target = ufshcd_devfreq_target,
5428 .get_dev_status = ufshcd_devfreq_get_dev_status,
5432 * ufshcd_init - Driver initialization routine
5433 * @hba: per-adapter instance
5434 * @mmio_base: base register address
5435 * @irq: Interrupt line of device
5436 * Returns 0 on success, non-zero value on failure
5438 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
5441 struct Scsi_Host *host = hba->host;
5442 struct device *dev = hba->dev;
5446 "Invalid memory reference for mmio_base is NULL\n");
5451 hba->mmio_base = mmio_base;
5454 err = ufshcd_hba_init(hba);
5458 /* Read capabilities registers */
5459 ufshcd_hba_capabilities(hba);
5461 /* Get UFS version supported by the controller */
5462 hba->ufs_version = ufshcd_get_ufs_version(hba);
5464 /* Get Interrupt bit mask per version */
5465 hba->intr_mask = ufshcd_get_intr_mask(hba);
5467 err = ufshcd_set_dma_mask(hba);
5469 dev_err(hba->dev, "set dma mask failed\n");
5473 /* Allocate memory for host memory space */
5474 err = ufshcd_memory_alloc(hba);
5476 dev_err(hba->dev, "Memory allocation failed\n");
5481 ufshcd_host_memory_configure(hba);
5483 host->can_queue = hba->nutrs;
5484 host->cmd_per_lun = hba->nutrs;
5485 host->max_id = UFSHCD_MAX_ID;
5486 host->max_lun = UFS_MAX_LUNS;
5487 host->max_channel = UFSHCD_MAX_CHANNEL;
5488 host->unique_id = host->host_no;
5489 host->max_cmd_len = MAX_CDB_SIZE;
5491 hba->max_pwr_info.is_valid = false;
5493 /* Initailize wait queue for task management */
5494 init_waitqueue_head(&hba->tm_wq);
5495 init_waitqueue_head(&hba->tm_tag_wq);
5497 /* Initialize work queues */
5498 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
5499 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
5501 /* Initialize UIC command mutex */
5502 mutex_init(&hba->uic_cmd_mutex);
5504 /* Initialize mutex for device management commands */
5505 mutex_init(&hba->dev_cmd.lock);
5507 /* Initialize device management tag acquire wait queue */
5508 init_waitqueue_head(&hba->dev_cmd.tag_wq);
5510 ufshcd_init_clk_gating(hba);
5511 /* IRQ registration */
5512 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
5514 dev_err(hba->dev, "request irq failed\n");
5517 hba->is_irq_enabled = true;
5520 /* Enable SCSI tag mapping */
5521 err = scsi_init_shared_tag_map(host, host->can_queue);
5523 dev_err(hba->dev, "init shared queue failed\n");
5527 err = scsi_add_host(host, hba->dev);
5529 dev_err(hba->dev, "scsi_add_host failed\n");
5533 /* Host controller enable */
5534 err = ufshcd_hba_enable(hba);
5536 dev_err(hba->dev, "Host controller enable failed\n");
5537 goto out_remove_scsi_host;
5540 if (ufshcd_is_clkscaling_enabled(hba)) {
5541 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
5542 "simple_ondemand", NULL);
5543 if (IS_ERR(hba->devfreq)) {
5544 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
5545 PTR_ERR(hba->devfreq));
5546 goto out_remove_scsi_host;
5548 /* Suspend devfreq until the UFS device is detected */
5549 devfreq_suspend_device(hba->devfreq);
5550 hba->clk_scaling.window_start_t = 0;
5553 /* Hold auto suspend until async scan completes */
5554 pm_runtime_get_sync(dev);
5557 * The device-initialize-sequence hasn't been invoked yet.
5558 * Set the device to power-off state
5560 ufshcd_set_ufs_dev_poweroff(hba);
5562 async_schedule(ufshcd_async_scan, hba);
5566 out_remove_scsi_host:
5567 scsi_remove_host(hba->host);
5569 ufshcd_exit_clk_gating(hba);
5571 hba->is_irq_enabled = false;
5572 scsi_host_put(host);
5573 ufshcd_hba_exit(hba);
5577 EXPORT_SYMBOL_GPL(ufshcd_init);
5579 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
5580 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
5581 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
5582 MODULE_LICENSE("GPL");
5583 MODULE_VERSION(UFSHCD_DRIVER_VERSION);