80031e6a63f59cc4e6aebf1f31619fac0ecd41c6
[cascardo/linux.git] / drivers / scsi / ufs / ufshcd.c
1 /*
2  * Universal Flash Storage Host controller driver Core
3  *
4  * This code is based on drivers/scsi/ufs/ufshcd.c
5  * Copyright (C) 2011-2013 Samsung India Software Operations
6  * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
7  *
8  * Authors:
9  *      Santosh Yaraganavi <santosh.sy@samsung.com>
10  *      Vinayak Holikatti <h.vinayak@samsung.com>
11  *
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>
18  *
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.
23  *
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
34  * this program.
35  *
36  * The Linux Foundation chooses to take subject only to the GPLv2
37  * license terms, and distributes only under these terms.
38  */
39
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42
43 #include <linux/of.h>
44 #include "ufshcd.h"
45 #include "unipro.h"
46
47 #define UFSHCD_ENABLE_INTRS     (UTP_TRANSFER_REQ_COMPL |\
48                                  UTP_TASK_REQ_COMPL |\
49                                  UFSHCD_ERROR_MASK)
50 /* UIC command timeout, unit: ms */
51 #define UIC_CMD_TIMEOUT 500
52
53 /* NOP OUT retries waiting for NOP IN response */
54 #define NOP_OUT_RETRIES    10
55 /* Timeout after 30 msecs if NOP OUT hangs without response */
56 #define NOP_OUT_TIMEOUT    30 /* msecs */
57
58 /* Query request retries */
59 #define QUERY_REQ_RETRIES 10
60 /* Query request timeout */
61 #define QUERY_REQ_TIMEOUT 30 /* msec */
62 /*
63  * Query request timeout for fDeviceInit flag
64  * fDeviceInit query response time for some devices is too large that default
65  * QUERY_REQ_TIMEOUT may not be enough for such devices.
66  */
67 #define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
68
69 /* Task management command timeout */
70 #define TM_CMD_TIMEOUT  100 /* msecs */
71
72 /* maximum number of retries for a general UIC command  */
73 #define UFS_UIC_COMMAND_RETRIES 3
74
75 /* maximum number of link-startup retries */
76 #define DME_LINKSTARTUP_RETRIES 3
77
78 /* Maximum retries for Hibern8 enter */
79 #define UIC_HIBERN8_ENTER_RETRIES 3
80
81 /* maximum number of reset retries before giving up */
82 #define MAX_HOST_RESET_RETRIES 5
83
84 /* Expose the flag value from utp_upiu_query.value */
85 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
86
87 /* Interrupt aggregation default timeout, unit: 40us */
88 #define INT_AGGR_DEF_TO 0x02
89
90 #define ufshcd_toggle_vreg(_dev, _vreg, _on)                            \
91         ({                                                              \
92                 int _ret;                                               \
93                 if (_on)                                                \
94                         _ret = ufshcd_enable_vreg(_dev, _vreg);         \
95                 else                                                    \
96                         _ret = ufshcd_disable_vreg(_dev, _vreg);        \
97                 _ret;                                                   \
98         })
99
100 static u32 ufs_query_desc_max_size[] = {
101         QUERY_DESC_DEVICE_MAX_SIZE,
102         QUERY_DESC_CONFIGURAION_MAX_SIZE,
103         QUERY_DESC_UNIT_MAX_SIZE,
104         QUERY_DESC_RFU_MAX_SIZE,
105         QUERY_DESC_INTERCONNECT_MAX_SIZE,
106         QUERY_DESC_STRING_MAX_SIZE,
107         QUERY_DESC_RFU_MAX_SIZE,
108         QUERY_DESC_GEOMETRY_MAX_SIZE,
109         QUERY_DESC_POWER_MAX_SIZE,
110         QUERY_DESC_RFU_MAX_SIZE,
111 };
112
113 enum {
114         UFSHCD_MAX_CHANNEL      = 0,
115         UFSHCD_MAX_ID           = 1,
116         UFSHCD_CMD_PER_LUN      = 32,
117         UFSHCD_CAN_QUEUE        = 32,
118 };
119
120 /* UFSHCD states */
121 enum {
122         UFSHCD_STATE_RESET,
123         UFSHCD_STATE_ERROR,
124         UFSHCD_STATE_OPERATIONAL,
125 };
126
127 /* UFSHCD error handling flags */
128 enum {
129         UFSHCD_EH_IN_PROGRESS = (1 << 0),
130 };
131
132 /* UFSHCD UIC layer error flags */
133 enum {
134         UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
135         UFSHCD_UIC_NL_ERROR = (1 << 1), /* Network layer error */
136         UFSHCD_UIC_TL_ERROR = (1 << 2), /* Transport Layer error */
137         UFSHCD_UIC_DME_ERROR = (1 << 3), /* DME error */
138 };
139
140 /* Interrupt configuration options */
141 enum {
142         UFSHCD_INT_DISABLE,
143         UFSHCD_INT_ENABLE,
144         UFSHCD_INT_CLEAR,
145 };
146
147 #define ufshcd_set_eh_in_progress(h) \
148         (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
149 #define ufshcd_eh_in_progress(h) \
150         (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
151 #define ufshcd_clear_eh_in_progress(h) \
152         (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
153
154 #define ufshcd_set_ufs_dev_active(h) \
155         ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
156 #define ufshcd_set_ufs_dev_sleep(h) \
157         ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
158 #define ufshcd_set_ufs_dev_poweroff(h) \
159         ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
160 #define ufshcd_is_ufs_dev_active(h) \
161         ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
162 #define ufshcd_is_ufs_dev_sleep(h) \
163         ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
164 #define ufshcd_is_ufs_dev_poweroff(h) \
165         ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
166
167 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
168         {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
169         {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
170         {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
171         {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
172         {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
173         {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
174 };
175
176 static inline enum ufs_dev_pwr_mode
177 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
178 {
179         return ufs_pm_lvl_states[lvl].dev_state;
180 }
181
182 static inline enum uic_link_state
183 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
184 {
185         return ufs_pm_lvl_states[lvl].link_state;
186 }
187
188 static void ufshcd_tmc_handler(struct ufs_hba *hba);
189 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
190 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
191 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
192 static void ufshcd_hba_exit(struct ufs_hba *hba);
193 static int ufshcd_probe_hba(struct ufs_hba *hba);
194 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
195                                  bool skip_ref_clk);
196 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
197 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
198 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
199 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
200 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
201 static irqreturn_t ufshcd_intr(int irq, void *__hba);
202 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
203                 struct ufs_pa_layer_attr *desired_pwr_mode);
204 static int ufshcd_change_power_mode(struct ufs_hba *hba,
205                              struct ufs_pa_layer_attr *pwr_mode);
206 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
207 {
208         return tag >= 0 && tag < hba->nutrs;
209 }
210
211 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
212 {
213         int ret = 0;
214
215         if (!hba->is_irq_enabled) {
216                 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
217                                 hba);
218                 if (ret)
219                         dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
220                                 __func__, ret);
221                 hba->is_irq_enabled = true;
222         }
223
224         return ret;
225 }
226
227 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
228 {
229         if (hba->is_irq_enabled) {
230                 free_irq(hba->irq, hba);
231                 hba->is_irq_enabled = false;
232         }
233 }
234
235 /*
236  * ufshcd_wait_for_register - wait for register value to change
237  * @hba - per-adapter interface
238  * @reg - mmio register offset
239  * @mask - mask to apply to read register value
240  * @val - wait condition
241  * @interval_us - polling interval in microsecs
242  * @timeout_ms - timeout in millisecs
243  * @can_sleep - perform sleep or just spin
244  *
245  * Returns -ETIMEDOUT on error, zero on success
246  */
247 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
248                                 u32 val, unsigned long interval_us,
249                                 unsigned long timeout_ms, bool can_sleep)
250 {
251         int err = 0;
252         unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
253
254         /* ignore bits that we don't intend to wait on */
255         val = val & mask;
256
257         while ((ufshcd_readl(hba, reg) & mask) != val) {
258                 if (can_sleep)
259                         usleep_range(interval_us, interval_us + 50);
260                 else
261                         udelay(interval_us);
262                 if (time_after(jiffies, timeout)) {
263                         if ((ufshcd_readl(hba, reg) & mask) != val)
264                                 err = -ETIMEDOUT;
265                         break;
266                 }
267         }
268
269         return err;
270 }
271
272 /**
273  * ufshcd_get_intr_mask - Get the interrupt bit mask
274  * @hba - Pointer to adapter instance
275  *
276  * Returns interrupt bit mask per version
277  */
278 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
279 {
280         if (hba->ufs_version == UFSHCI_VERSION_10)
281                 return INTERRUPT_MASK_ALL_VER_10;
282         else
283                 return INTERRUPT_MASK_ALL_VER_11;
284 }
285
286 /**
287  * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
288  * @hba - Pointer to adapter instance
289  *
290  * Returns UFSHCI version supported by the controller
291  */
292 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
293 {
294         if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
295                 return ufshcd_vops_get_ufs_hci_version(hba);
296
297         return ufshcd_readl(hba, REG_UFS_VERSION);
298 }
299
300 /**
301  * ufshcd_is_device_present - Check if any device connected to
302  *                            the host controller
303  * @hba: pointer to adapter instance
304  *
305  * Returns 1 if device present, 0 if no device detected
306  */
307 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
308 {
309         return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
310                                                 DEVICE_PRESENT) ? 1 : 0;
311 }
312
313 /**
314  * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
315  * @lrb: pointer to local command reference block
316  *
317  * This function is used to get the OCS field from UTRD
318  * Returns the OCS field in the UTRD
319  */
320 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
321 {
322         return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
323 }
324
325 /**
326  * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
327  * @task_req_descp: pointer to utp_task_req_desc structure
328  *
329  * This function is used to get the OCS field from UTMRD
330  * Returns the OCS field in the UTMRD
331  */
332 static inline int
333 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
334 {
335         return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
336 }
337
338 /**
339  * ufshcd_get_tm_free_slot - get a free slot for task management request
340  * @hba: per adapter instance
341  * @free_slot: pointer to variable with available slot value
342  *
343  * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
344  * Returns 0 if free slot is not available, else return 1 with tag value
345  * in @free_slot.
346  */
347 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
348 {
349         int tag;
350         bool ret = false;
351
352         if (!free_slot)
353                 goto out;
354
355         do {
356                 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
357                 if (tag >= hba->nutmrs)
358                         goto out;
359         } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
360
361         *free_slot = tag;
362         ret = true;
363 out:
364         return ret;
365 }
366
367 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
368 {
369         clear_bit_unlock(slot, &hba->tm_slots_in_use);
370 }
371
372 /**
373  * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
374  * @hba: per adapter instance
375  * @pos: position of the bit to be cleared
376  */
377 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
378 {
379         ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
380 }
381
382 /**
383  * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
384  * @hba: per adapter instance
385  * @tag: position of the bit to be cleared
386  */
387 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
388 {
389         __clear_bit(tag, &hba->outstanding_reqs);
390 }
391
392 /**
393  * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
394  * @reg: Register value of host controller status
395  *
396  * Returns integer, 0 on Success and positive value if failed
397  */
398 static inline int ufshcd_get_lists_status(u32 reg)
399 {
400         /*
401          * The mask 0xFF is for the following HCS register bits
402          * Bit          Description
403          *  0           Device Present
404          *  1           UTRLRDY
405          *  2           UTMRLRDY
406          *  3           UCRDY
407          * 4-7          reserved
408          */
409         return ((reg & 0xFF) >> 1) ^ 0x07;
410 }
411
412 /**
413  * ufshcd_get_uic_cmd_result - Get the UIC command result
414  * @hba: Pointer to adapter instance
415  *
416  * This function gets the result of UIC command completion
417  * Returns 0 on success, non zero value on error
418  */
419 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
420 {
421         return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
422                MASK_UIC_COMMAND_RESULT;
423 }
424
425 /**
426  * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
427  * @hba: Pointer to adapter instance
428  *
429  * This function gets UIC command argument3
430  * Returns 0 on success, non zero value on error
431  */
432 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
433 {
434         return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
435 }
436
437 /**
438  * ufshcd_get_req_rsp - returns the TR response transaction type
439  * @ucd_rsp_ptr: pointer to response UPIU
440  */
441 static inline int
442 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
443 {
444         return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
445 }
446
447 /**
448  * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
449  * @ucd_rsp_ptr: pointer to response UPIU
450  *
451  * This function gets the response status and scsi_status from response UPIU
452  * Returns the response result code.
453  */
454 static inline int
455 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
456 {
457         return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
458 }
459
460 /*
461  * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
462  *                              from response UPIU
463  * @ucd_rsp_ptr: pointer to response UPIU
464  *
465  * Return the data segment length.
466  */
467 static inline unsigned int
468 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
469 {
470         return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
471                 MASK_RSP_UPIU_DATA_SEG_LEN;
472 }
473
474 /**
475  * ufshcd_is_exception_event - Check if the device raised an exception event
476  * @ucd_rsp_ptr: pointer to response UPIU
477  *
478  * The function checks if the device raised an exception event indicated in
479  * the Device Information field of response UPIU.
480  *
481  * Returns true if exception is raised, false otherwise.
482  */
483 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
484 {
485         return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
486                         MASK_RSP_EXCEPTION_EVENT ? true : false;
487 }
488
489 /**
490  * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
491  * @hba: per adapter instance
492  */
493 static inline void
494 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
495 {
496         ufshcd_writel(hba, INT_AGGR_ENABLE |
497                       INT_AGGR_COUNTER_AND_TIMER_RESET,
498                       REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
499 }
500
501 /**
502  * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
503  * @hba: per adapter instance
504  * @cnt: Interrupt aggregation counter threshold
505  * @tmout: Interrupt aggregation timeout value
506  */
507 static inline void
508 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
509 {
510         ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
511                       INT_AGGR_COUNTER_THLD_VAL(cnt) |
512                       INT_AGGR_TIMEOUT_VAL(tmout),
513                       REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
514 }
515
516 /**
517  * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
518  * @hba: per adapter instance
519  */
520 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
521 {
522         ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
523 }
524
525 /**
526  * ufshcd_enable_run_stop_reg - Enable run-stop registers,
527  *                      When run-stop registers are set to 1, it indicates the
528  *                      host controller that it can process the requests
529  * @hba: per adapter instance
530  */
531 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
532 {
533         ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
534                       REG_UTP_TASK_REQ_LIST_RUN_STOP);
535         ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
536                       REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
537 }
538
539 /**
540  * ufshcd_hba_start - Start controller initialization sequence
541  * @hba: per adapter instance
542  */
543 static inline void ufshcd_hba_start(struct ufs_hba *hba)
544 {
545         ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
546 }
547
548 /**
549  * ufshcd_is_hba_active - Get controller state
550  * @hba: per adapter instance
551  *
552  * Returns zero if controller is active, 1 otherwise
553  */
554 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
555 {
556         return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
557 }
558
559 static void ufshcd_ungate_work(struct work_struct *work)
560 {
561         int ret;
562         unsigned long flags;
563         struct ufs_hba *hba = container_of(work, struct ufs_hba,
564                         clk_gating.ungate_work);
565
566         cancel_delayed_work_sync(&hba->clk_gating.gate_work);
567
568         spin_lock_irqsave(hba->host->host_lock, flags);
569         if (hba->clk_gating.state == CLKS_ON) {
570                 spin_unlock_irqrestore(hba->host->host_lock, flags);
571                 goto unblock_reqs;
572         }
573
574         spin_unlock_irqrestore(hba->host->host_lock, flags);
575         ufshcd_setup_clocks(hba, true);
576
577         /* Exit from hibern8 */
578         if (ufshcd_can_hibern8_during_gating(hba)) {
579                 /* Prevent gating in this path */
580                 hba->clk_gating.is_suspended = true;
581                 if (ufshcd_is_link_hibern8(hba)) {
582                         ret = ufshcd_uic_hibern8_exit(hba);
583                         if (ret)
584                                 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
585                                         __func__, ret);
586                         else
587                                 ufshcd_set_link_active(hba);
588                 }
589                 hba->clk_gating.is_suspended = false;
590         }
591 unblock_reqs:
592         if (ufshcd_is_clkscaling_enabled(hba))
593                 devfreq_resume_device(hba->devfreq);
594         scsi_unblock_requests(hba->host);
595 }
596
597 /**
598  * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
599  * Also, exit from hibern8 mode and set the link as active.
600  * @hba: per adapter instance
601  * @async: This indicates whether caller should ungate clocks asynchronously.
602  */
603 int ufshcd_hold(struct ufs_hba *hba, bool async)
604 {
605         int rc = 0;
606         unsigned long flags;
607
608         if (!ufshcd_is_clkgating_allowed(hba))
609                 goto out;
610         spin_lock_irqsave(hba->host->host_lock, flags);
611         hba->clk_gating.active_reqs++;
612
613         if (ufshcd_eh_in_progress(hba)) {
614                 spin_unlock_irqrestore(hba->host->host_lock, flags);
615                 return 0;
616         }
617
618 start:
619         switch (hba->clk_gating.state) {
620         case CLKS_ON:
621                 break;
622         case REQ_CLKS_OFF:
623                 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
624                         hba->clk_gating.state = CLKS_ON;
625                         break;
626                 }
627                 /*
628                  * If we here, it means gating work is either done or
629                  * currently running. Hence, fall through to cancel gating
630                  * work and to enable clocks.
631                  */
632         case CLKS_OFF:
633                 scsi_block_requests(hba->host);
634                 hba->clk_gating.state = REQ_CLKS_ON;
635                 schedule_work(&hba->clk_gating.ungate_work);
636                 /*
637                  * fall through to check if we should wait for this
638                  * work to be done or not.
639                  */
640         case REQ_CLKS_ON:
641                 if (async) {
642                         rc = -EAGAIN;
643                         hba->clk_gating.active_reqs--;
644                         break;
645                 }
646
647                 spin_unlock_irqrestore(hba->host->host_lock, flags);
648                 flush_work(&hba->clk_gating.ungate_work);
649                 /* Make sure state is CLKS_ON before returning */
650                 spin_lock_irqsave(hba->host->host_lock, flags);
651                 goto start;
652         default:
653                 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
654                                 __func__, hba->clk_gating.state);
655                 break;
656         }
657         spin_unlock_irqrestore(hba->host->host_lock, flags);
658 out:
659         return rc;
660 }
661 EXPORT_SYMBOL_GPL(ufshcd_hold);
662
663 static void ufshcd_gate_work(struct work_struct *work)
664 {
665         struct ufs_hba *hba = container_of(work, struct ufs_hba,
666                         clk_gating.gate_work.work);
667         unsigned long flags;
668
669         spin_lock_irqsave(hba->host->host_lock, flags);
670         if (hba->clk_gating.is_suspended) {
671                 hba->clk_gating.state = CLKS_ON;
672                 goto rel_lock;
673         }
674
675         if (hba->clk_gating.active_reqs
676                 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
677                 || hba->lrb_in_use || hba->outstanding_tasks
678                 || hba->active_uic_cmd || hba->uic_async_done)
679                 goto rel_lock;
680
681         spin_unlock_irqrestore(hba->host->host_lock, flags);
682
683         /* put the link into hibern8 mode before turning off clocks */
684         if (ufshcd_can_hibern8_during_gating(hba)) {
685                 if (ufshcd_uic_hibern8_enter(hba)) {
686                         hba->clk_gating.state = CLKS_ON;
687                         goto out;
688                 }
689                 ufshcd_set_link_hibern8(hba);
690         }
691
692         if (ufshcd_is_clkscaling_enabled(hba)) {
693                 devfreq_suspend_device(hba->devfreq);
694                 hba->clk_scaling.window_start_t = 0;
695         }
696
697         if (!ufshcd_is_link_active(hba))
698                 ufshcd_setup_clocks(hba, false);
699         else
700                 /* If link is active, device ref_clk can't be switched off */
701                 __ufshcd_setup_clocks(hba, false, true);
702
703         /*
704          * In case you are here to cancel this work the gating state
705          * would be marked as REQ_CLKS_ON. In this case keep the state
706          * as REQ_CLKS_ON which would anyway imply that clocks are off
707          * and a request to turn them on is pending. By doing this way,
708          * we keep the state machine in tact and this would ultimately
709          * prevent from doing cancel work multiple times when there are
710          * new requests arriving before the current cancel work is done.
711          */
712         spin_lock_irqsave(hba->host->host_lock, flags);
713         if (hba->clk_gating.state == REQ_CLKS_OFF)
714                 hba->clk_gating.state = CLKS_OFF;
715
716 rel_lock:
717         spin_unlock_irqrestore(hba->host->host_lock, flags);
718 out:
719         return;
720 }
721
722 /* host lock must be held before calling this variant */
723 static void __ufshcd_release(struct ufs_hba *hba)
724 {
725         if (!ufshcd_is_clkgating_allowed(hba))
726                 return;
727
728         hba->clk_gating.active_reqs--;
729
730         if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
731                 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
732                 || hba->lrb_in_use || hba->outstanding_tasks
733                 || hba->active_uic_cmd || hba->uic_async_done
734                 || ufshcd_eh_in_progress(hba))
735                 return;
736
737         hba->clk_gating.state = REQ_CLKS_OFF;
738         schedule_delayed_work(&hba->clk_gating.gate_work,
739                         msecs_to_jiffies(hba->clk_gating.delay_ms));
740 }
741
742 void ufshcd_release(struct ufs_hba *hba)
743 {
744         unsigned long flags;
745
746         spin_lock_irqsave(hba->host->host_lock, flags);
747         __ufshcd_release(hba);
748         spin_unlock_irqrestore(hba->host->host_lock, flags);
749 }
750 EXPORT_SYMBOL_GPL(ufshcd_release);
751
752 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
753                 struct device_attribute *attr, char *buf)
754 {
755         struct ufs_hba *hba = dev_get_drvdata(dev);
756
757         return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
758 }
759
760 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
761                 struct device_attribute *attr, const char *buf, size_t count)
762 {
763         struct ufs_hba *hba = dev_get_drvdata(dev);
764         unsigned long flags, value;
765
766         if (kstrtoul(buf, 0, &value))
767                 return -EINVAL;
768
769         spin_lock_irqsave(hba->host->host_lock, flags);
770         hba->clk_gating.delay_ms = value;
771         spin_unlock_irqrestore(hba->host->host_lock, flags);
772         return count;
773 }
774
775 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
776 {
777         if (!ufshcd_is_clkgating_allowed(hba))
778                 return;
779
780         hba->clk_gating.delay_ms = 150;
781         INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
782         INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
783
784         hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
785         hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
786         sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
787         hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
788         hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
789         if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
790                 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
791 }
792
793 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
794 {
795         if (!ufshcd_is_clkgating_allowed(hba))
796                 return;
797         device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
798         cancel_work_sync(&hba->clk_gating.ungate_work);
799         cancel_delayed_work_sync(&hba->clk_gating.gate_work);
800 }
801
802 /* Must be called with host lock acquired */
803 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
804 {
805         if (!ufshcd_is_clkscaling_enabled(hba))
806                 return;
807
808         if (!hba->clk_scaling.is_busy_started) {
809                 hba->clk_scaling.busy_start_t = ktime_get();
810                 hba->clk_scaling.is_busy_started = true;
811         }
812 }
813
814 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
815 {
816         struct ufs_clk_scaling *scaling = &hba->clk_scaling;
817
818         if (!ufshcd_is_clkscaling_enabled(hba))
819                 return;
820
821         if (!hba->outstanding_reqs && scaling->is_busy_started) {
822                 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
823                                         scaling->busy_start_t));
824                 scaling->busy_start_t = ktime_set(0, 0);
825                 scaling->is_busy_started = false;
826         }
827 }
828 /**
829  * ufshcd_send_command - Send SCSI or device management commands
830  * @hba: per adapter instance
831  * @task_tag: Task tag of the command
832  */
833 static inline
834 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
835 {
836         ufshcd_clk_scaling_start_busy(hba);
837         __set_bit(task_tag, &hba->outstanding_reqs);
838         ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
839 }
840
841 /**
842  * ufshcd_copy_sense_data - Copy sense data in case of check condition
843  * @lrb - pointer to local reference block
844  */
845 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
846 {
847         int len;
848         if (lrbp->sense_buffer &&
849             ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
850                 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
851                 memcpy(lrbp->sense_buffer,
852                         lrbp->ucd_rsp_ptr->sr.sense_data,
853                         min_t(int, len, SCSI_SENSE_BUFFERSIZE));
854         }
855 }
856
857 /**
858  * ufshcd_copy_query_response() - Copy the Query Response and the data
859  * descriptor
860  * @hba: per adapter instance
861  * @lrb - pointer to local reference block
862  */
863 static
864 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
865 {
866         struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
867
868         memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
869
870         /* Get the descriptor */
871         if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
872                 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
873                                 GENERAL_UPIU_REQUEST_SIZE;
874                 u16 resp_len;
875                 u16 buf_len;
876
877                 /* data segment length */
878                 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
879                                                 MASK_QUERY_DATA_SEG_LEN;
880                 buf_len = be16_to_cpu(
881                                 hba->dev_cmd.query.request.upiu_req.length);
882                 if (likely(buf_len >= resp_len)) {
883                         memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
884                 } else {
885                         dev_warn(hba->dev,
886                                 "%s: Response size is bigger than buffer",
887                                 __func__);
888                         return -EINVAL;
889                 }
890         }
891
892         return 0;
893 }
894
895 /**
896  * ufshcd_hba_capabilities - Read controller capabilities
897  * @hba: per adapter instance
898  */
899 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
900 {
901         hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
902
903         /* nutrs and nutmrs are 0 based values */
904         hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
905         hba->nutmrs =
906         ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
907 }
908
909 /**
910  * ufshcd_ready_for_uic_cmd - Check if controller is ready
911  *                            to accept UIC commands
912  * @hba: per adapter instance
913  * Return true on success, else false
914  */
915 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
916 {
917         if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
918                 return true;
919         else
920                 return false;
921 }
922
923 /**
924  * ufshcd_get_upmcrs - Get the power mode change request status
925  * @hba: Pointer to adapter instance
926  *
927  * This function gets the UPMCRS field of HCS register
928  * Returns value of UPMCRS field
929  */
930 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
931 {
932         return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
933 }
934
935 /**
936  * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
937  * @hba: per adapter instance
938  * @uic_cmd: UIC command
939  *
940  * Mutex must be held.
941  */
942 static inline void
943 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
944 {
945         WARN_ON(hba->active_uic_cmd);
946
947         hba->active_uic_cmd = uic_cmd;
948
949         /* Write Args */
950         ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
951         ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
952         ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
953
954         /* Write UIC Cmd */
955         ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
956                       REG_UIC_COMMAND);
957 }
958
959 /**
960  * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
961  * @hba: per adapter instance
962  * @uic_command: UIC command
963  *
964  * Must be called with mutex held.
965  * Returns 0 only if success.
966  */
967 static int
968 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
969 {
970         int ret;
971         unsigned long flags;
972
973         if (wait_for_completion_timeout(&uic_cmd->done,
974                                         msecs_to_jiffies(UIC_CMD_TIMEOUT)))
975                 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
976         else
977                 ret = -ETIMEDOUT;
978
979         spin_lock_irqsave(hba->host->host_lock, flags);
980         hba->active_uic_cmd = NULL;
981         spin_unlock_irqrestore(hba->host->host_lock, flags);
982
983         return ret;
984 }
985
986 /**
987  * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
988  * @hba: per adapter instance
989  * @uic_cmd: UIC command
990  * @completion: initialize the completion only if this is set to true
991  *
992  * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
993  * with mutex held and host_lock locked.
994  * Returns 0 only if success.
995  */
996 static int
997 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
998                       bool completion)
999 {
1000         if (!ufshcd_ready_for_uic_cmd(hba)) {
1001                 dev_err(hba->dev,
1002                         "Controller not ready to accept UIC commands\n");
1003                 return -EIO;
1004         }
1005
1006         if (completion)
1007                 init_completion(&uic_cmd->done);
1008
1009         ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1010
1011         return 0;
1012 }
1013
1014 /**
1015  * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1016  * @hba: per adapter instance
1017  * @uic_cmd: UIC command
1018  *
1019  * Returns 0 only if success.
1020  */
1021 static int
1022 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1023 {
1024         int ret;
1025         unsigned long flags;
1026
1027         ufshcd_hold(hba, false);
1028         mutex_lock(&hba->uic_cmd_mutex);
1029         ufshcd_add_delay_before_dme_cmd(hba);
1030
1031         spin_lock_irqsave(hba->host->host_lock, flags);
1032         ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1033         spin_unlock_irqrestore(hba->host->host_lock, flags);
1034         if (!ret)
1035                 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1036
1037         mutex_unlock(&hba->uic_cmd_mutex);
1038
1039         ufshcd_release(hba);
1040         return ret;
1041 }
1042
1043 /**
1044  * ufshcd_map_sg - Map scatter-gather list to prdt
1045  * @lrbp - pointer to local reference block
1046  *
1047  * Returns 0 in case of success, non-zero value in case of failure
1048  */
1049 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1050 {
1051         struct ufshcd_sg_entry *prd_table;
1052         struct scatterlist *sg;
1053         struct scsi_cmnd *cmd;
1054         int sg_segments;
1055         int i;
1056
1057         cmd = lrbp->cmd;
1058         sg_segments = scsi_dma_map(cmd);
1059         if (sg_segments < 0)
1060                 return sg_segments;
1061
1062         if (sg_segments) {
1063                 lrbp->utr_descriptor_ptr->prd_table_length =
1064                                         cpu_to_le16((u16) (sg_segments));
1065
1066                 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1067
1068                 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1069                         prd_table[i].size  =
1070                                 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1071                         prd_table[i].base_addr =
1072                                 cpu_to_le32(lower_32_bits(sg->dma_address));
1073                         prd_table[i].upper_addr =
1074                                 cpu_to_le32(upper_32_bits(sg->dma_address));
1075                         prd_table[i].reserved = 0;
1076                 }
1077         } else {
1078                 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1079         }
1080
1081         return 0;
1082 }
1083
1084 /**
1085  * ufshcd_enable_intr - enable interrupts
1086  * @hba: per adapter instance
1087  * @intrs: interrupt bits
1088  */
1089 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1090 {
1091         u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1092
1093         if (hba->ufs_version == UFSHCI_VERSION_10) {
1094                 u32 rw;
1095                 rw = set & INTERRUPT_MASK_RW_VER_10;
1096                 set = rw | ((set ^ intrs) & intrs);
1097         } else {
1098                 set |= intrs;
1099         }
1100
1101         ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1102 }
1103
1104 /**
1105  * ufshcd_disable_intr - disable interrupts
1106  * @hba: per adapter instance
1107  * @intrs: interrupt bits
1108  */
1109 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1110 {
1111         u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1112
1113         if (hba->ufs_version == UFSHCI_VERSION_10) {
1114                 u32 rw;
1115                 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1116                         ~(intrs & INTERRUPT_MASK_RW_VER_10);
1117                 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1118
1119         } else {
1120                 set &= ~intrs;
1121         }
1122
1123         ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1124 }
1125
1126 /**
1127  * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1128  * descriptor according to request
1129  * @lrbp: pointer to local reference block
1130  * @upiu_flags: flags required in the header
1131  * @cmd_dir: requests data direction
1132  */
1133 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1134                 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1135 {
1136         struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1137         u32 data_direction;
1138         u32 dword_0;
1139
1140         if (cmd_dir == DMA_FROM_DEVICE) {
1141                 data_direction = UTP_DEVICE_TO_HOST;
1142                 *upiu_flags = UPIU_CMD_FLAGS_READ;
1143         } else if (cmd_dir == DMA_TO_DEVICE) {
1144                 data_direction = UTP_HOST_TO_DEVICE;
1145                 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1146         } else {
1147                 data_direction = UTP_NO_DATA_TRANSFER;
1148                 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1149         }
1150
1151         dword_0 = data_direction | (lrbp->command_type
1152                                 << UPIU_COMMAND_TYPE_OFFSET);
1153         if (lrbp->intr_cmd)
1154                 dword_0 |= UTP_REQ_DESC_INT_CMD;
1155
1156         /* Transfer request descriptor header fields */
1157         req_desc->header.dword_0 = cpu_to_le32(dword_0);
1158         /* dword_1 is reserved, hence it is set to 0 */
1159         req_desc->header.dword_1 = 0;
1160         /*
1161          * assigning invalid value for command status. Controller
1162          * updates OCS on command completion, with the command
1163          * status
1164          */
1165         req_desc->header.dword_2 =
1166                 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1167         /* dword_3 is reserved, hence it is set to 0 */
1168         req_desc->header.dword_3 = 0;
1169
1170         req_desc->prd_table_length = 0;
1171 }
1172
1173 /**
1174  * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1175  * for scsi commands
1176  * @lrbp - local reference block pointer
1177  * @upiu_flags - flags
1178  */
1179 static
1180 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1181 {
1182         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1183         unsigned short cdb_len;
1184
1185         /* command descriptor fields */
1186         ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1187                                 UPIU_TRANSACTION_COMMAND, upiu_flags,
1188                                 lrbp->lun, lrbp->task_tag);
1189         ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1190                                 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1191
1192         /* Total EHS length and Data segment length will be zero */
1193         ucd_req_ptr->header.dword_2 = 0;
1194
1195         ucd_req_ptr->sc.exp_data_transfer_len =
1196                 cpu_to_be32(lrbp->cmd->sdb.length);
1197
1198         cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1199         memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1200         memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1201
1202         memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1203 }
1204
1205 /**
1206  * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1207  * for query requsts
1208  * @hba: UFS hba
1209  * @lrbp: local reference block pointer
1210  * @upiu_flags: flags
1211  */
1212 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1213                                 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1214 {
1215         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1216         struct ufs_query *query = &hba->dev_cmd.query;
1217         u16 len = be16_to_cpu(query->request.upiu_req.length);
1218         u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1219
1220         /* Query request header */
1221         ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1222                         UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1223                         lrbp->lun, lrbp->task_tag);
1224         ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1225                         0, query->request.query_func, 0, 0);
1226
1227         /* Data segment length */
1228         ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1229                         0, 0, len >> 8, (u8)len);
1230
1231         /* Copy the Query Request buffer as is */
1232         memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1233                         QUERY_OSF_SIZE);
1234
1235         /* Copy the Descriptor */
1236         if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1237                 memcpy(descp, query->descriptor, len);
1238
1239         memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1240 }
1241
1242 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1243 {
1244         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1245
1246         memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1247
1248         /* command descriptor fields */
1249         ucd_req_ptr->header.dword_0 =
1250                 UPIU_HEADER_DWORD(
1251                         UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1252         /* clear rest of the fields of basic header */
1253         ucd_req_ptr->header.dword_1 = 0;
1254         ucd_req_ptr->header.dword_2 = 0;
1255
1256         memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1257 }
1258
1259 /**
1260  * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
1261  * @hba - per adapter instance
1262  * @lrb - pointer to local reference block
1263  */
1264 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1265 {
1266         u32 upiu_flags;
1267         int ret = 0;
1268
1269         switch (lrbp->command_type) {
1270         case UTP_CMD_TYPE_SCSI:
1271                 if (likely(lrbp->cmd)) {
1272                         ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1273                                         lrbp->cmd->sc_data_direction);
1274                         ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1275                 } else {
1276                         ret = -EINVAL;
1277                 }
1278                 break;
1279         case UTP_CMD_TYPE_DEV_MANAGE:
1280                 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1281                 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1282                         ufshcd_prepare_utp_query_req_upiu(
1283                                         hba, lrbp, upiu_flags);
1284                 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1285                         ufshcd_prepare_utp_nop_upiu(lrbp);
1286                 else
1287                         ret = -EINVAL;
1288                 break;
1289         case UTP_CMD_TYPE_UFS:
1290                 /* For UFS native command implementation */
1291                 ret = -ENOTSUPP;
1292                 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1293                         __func__);
1294                 break;
1295         default:
1296                 ret = -ENOTSUPP;
1297                 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1298                                 __func__, lrbp->command_type);
1299                 break;
1300         } /* end of switch */
1301
1302         return ret;
1303 }
1304
1305 /*
1306  * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1307  * @scsi_lun: scsi LUN id
1308  *
1309  * Returns UPIU LUN id
1310  */
1311 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1312 {
1313         if (scsi_is_wlun(scsi_lun))
1314                 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1315                         | UFS_UPIU_WLUN_ID;
1316         else
1317                 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1318 }
1319
1320 /**
1321  * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1322  * @scsi_lun: UPIU W-LUN id
1323  *
1324  * Returns SCSI W-LUN id
1325  */
1326 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1327 {
1328         return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1329 }
1330
1331 /**
1332  * ufshcd_queuecommand - main entry point for SCSI requests
1333  * @cmd: command from SCSI Midlayer
1334  * @done: call back function
1335  *
1336  * Returns 0 for success, non-zero in case of failure
1337  */
1338 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1339 {
1340         struct ufshcd_lrb *lrbp;
1341         struct ufs_hba *hba;
1342         unsigned long flags;
1343         int tag;
1344         int err = 0;
1345
1346         hba = shost_priv(host);
1347
1348         tag = cmd->request->tag;
1349         if (!ufshcd_valid_tag(hba, tag)) {
1350                 dev_err(hba->dev,
1351                         "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1352                         __func__, tag, cmd, cmd->request);
1353                 BUG();
1354         }
1355
1356         spin_lock_irqsave(hba->host->host_lock, flags);
1357         switch (hba->ufshcd_state) {
1358         case UFSHCD_STATE_OPERATIONAL:
1359                 break;
1360         case UFSHCD_STATE_RESET:
1361                 err = SCSI_MLQUEUE_HOST_BUSY;
1362                 goto out_unlock;
1363         case UFSHCD_STATE_ERROR:
1364                 set_host_byte(cmd, DID_ERROR);
1365                 cmd->scsi_done(cmd);
1366                 goto out_unlock;
1367         default:
1368                 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1369                                 __func__, hba->ufshcd_state);
1370                 set_host_byte(cmd, DID_BAD_TARGET);
1371                 cmd->scsi_done(cmd);
1372                 goto out_unlock;
1373         }
1374
1375         /* if error handling is in progress, don't issue commands */
1376         if (ufshcd_eh_in_progress(hba)) {
1377                 set_host_byte(cmd, DID_ERROR);
1378                 cmd->scsi_done(cmd);
1379                 goto out_unlock;
1380         }
1381         spin_unlock_irqrestore(hba->host->host_lock, flags);
1382
1383         /* acquire the tag to make sure device cmds don't use it */
1384         if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1385                 /*
1386                  * Dev manage command in progress, requeue the command.
1387                  * Requeuing the command helps in cases where the request *may*
1388                  * find different tag instead of waiting for dev manage command
1389                  * completion.
1390                  */
1391                 err = SCSI_MLQUEUE_HOST_BUSY;
1392                 goto out;
1393         }
1394
1395         err = ufshcd_hold(hba, true);
1396         if (err) {
1397                 err = SCSI_MLQUEUE_HOST_BUSY;
1398                 clear_bit_unlock(tag, &hba->lrb_in_use);
1399                 goto out;
1400         }
1401         WARN_ON(hba->clk_gating.state != CLKS_ON);
1402
1403         lrbp = &hba->lrb[tag];
1404
1405         WARN_ON(lrbp->cmd);
1406         lrbp->cmd = cmd;
1407         lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1408         lrbp->sense_buffer = cmd->sense_buffer;
1409         lrbp->task_tag = tag;
1410         lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1411         lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1412         lrbp->command_type = UTP_CMD_TYPE_SCSI;
1413
1414         /* form UPIU before issuing the command */
1415         ufshcd_compose_upiu(hba, lrbp);
1416         err = ufshcd_map_sg(lrbp);
1417         if (err) {
1418                 lrbp->cmd = NULL;
1419                 clear_bit_unlock(tag, &hba->lrb_in_use);
1420                 goto out;
1421         }
1422
1423         /* issue command to the controller */
1424         spin_lock_irqsave(hba->host->host_lock, flags);
1425         ufshcd_send_command(hba, tag);
1426 out_unlock:
1427         spin_unlock_irqrestore(hba->host->host_lock, flags);
1428 out:
1429         return err;
1430 }
1431
1432 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1433                 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1434 {
1435         lrbp->cmd = NULL;
1436         lrbp->sense_bufflen = 0;
1437         lrbp->sense_buffer = NULL;
1438         lrbp->task_tag = tag;
1439         lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1440         lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1441         lrbp->intr_cmd = true; /* No interrupt aggregation */
1442         hba->dev_cmd.type = cmd_type;
1443
1444         return ufshcd_compose_upiu(hba, lrbp);
1445 }
1446
1447 static int
1448 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1449 {
1450         int err = 0;
1451         unsigned long flags;
1452         u32 mask = 1 << tag;
1453
1454         /* clear outstanding transaction before retry */
1455         spin_lock_irqsave(hba->host->host_lock, flags);
1456         ufshcd_utrl_clear(hba, tag);
1457         spin_unlock_irqrestore(hba->host->host_lock, flags);
1458
1459         /*
1460          * wait for for h/w to clear corresponding bit in door-bell.
1461          * max. wait is 1 sec.
1462          */
1463         err = ufshcd_wait_for_register(hba,
1464                         REG_UTP_TRANSFER_REQ_DOOR_BELL,
1465                         mask, ~mask, 1000, 1000, true);
1466
1467         return err;
1468 }
1469
1470 static int
1471 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1472 {
1473         struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1474
1475         /* Get the UPIU response */
1476         query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1477                                 UPIU_RSP_CODE_OFFSET;
1478         return query_res->response;
1479 }
1480
1481 /**
1482  * ufshcd_dev_cmd_completion() - handles device management command responses
1483  * @hba: per adapter instance
1484  * @lrbp: pointer to local reference block
1485  */
1486 static int
1487 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1488 {
1489         int resp;
1490         int err = 0;
1491
1492         resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1493
1494         switch (resp) {
1495         case UPIU_TRANSACTION_NOP_IN:
1496                 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1497                         err = -EINVAL;
1498                         dev_err(hba->dev, "%s: unexpected response %x\n",
1499                                         __func__, resp);
1500                 }
1501                 break;
1502         case UPIU_TRANSACTION_QUERY_RSP:
1503                 err = ufshcd_check_query_response(hba, lrbp);
1504                 if (!err)
1505                         err = ufshcd_copy_query_response(hba, lrbp);
1506                 break;
1507         case UPIU_TRANSACTION_REJECT_UPIU:
1508                 /* TODO: handle Reject UPIU Response */
1509                 err = -EPERM;
1510                 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1511                                 __func__);
1512                 break;
1513         default:
1514                 err = -EINVAL;
1515                 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1516                                 __func__, resp);
1517                 break;
1518         }
1519
1520         return err;
1521 }
1522
1523 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1524                 struct ufshcd_lrb *lrbp, int max_timeout)
1525 {
1526         int err = 0;
1527         unsigned long time_left;
1528         unsigned long flags;
1529
1530         time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1531                         msecs_to_jiffies(max_timeout));
1532
1533         spin_lock_irqsave(hba->host->host_lock, flags);
1534         hba->dev_cmd.complete = NULL;
1535         if (likely(time_left)) {
1536                 err = ufshcd_get_tr_ocs(lrbp);
1537                 if (!err)
1538                         err = ufshcd_dev_cmd_completion(hba, lrbp);
1539         }
1540         spin_unlock_irqrestore(hba->host->host_lock, flags);
1541
1542         if (!time_left) {
1543                 err = -ETIMEDOUT;
1544                 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1545                         __func__, lrbp->task_tag);
1546                 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1547                         /* successfully cleared the command, retry if needed */
1548                         err = -EAGAIN;
1549                 /*
1550                  * in case of an error, after clearing the doorbell,
1551                  * we also need to clear the outstanding_request
1552                  * field in hba
1553                  */
1554                 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
1555         }
1556
1557         return err;
1558 }
1559
1560 /**
1561  * ufshcd_get_dev_cmd_tag - Get device management command tag
1562  * @hba: per-adapter instance
1563  * @tag: pointer to variable with available slot value
1564  *
1565  * Get a free slot and lock it until device management command
1566  * completes.
1567  *
1568  * Returns false if free slot is unavailable for locking, else
1569  * return true with tag value in @tag.
1570  */
1571 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1572 {
1573         int tag;
1574         bool ret = false;
1575         unsigned long tmp;
1576
1577         if (!tag_out)
1578                 goto out;
1579
1580         do {
1581                 tmp = ~hba->lrb_in_use;
1582                 tag = find_last_bit(&tmp, hba->nutrs);
1583                 if (tag >= hba->nutrs)
1584                         goto out;
1585         } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1586
1587         *tag_out = tag;
1588         ret = true;
1589 out:
1590         return ret;
1591 }
1592
1593 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1594 {
1595         clear_bit_unlock(tag, &hba->lrb_in_use);
1596 }
1597
1598 /**
1599  * ufshcd_exec_dev_cmd - API for sending device management requests
1600  * @hba - UFS hba
1601  * @cmd_type - specifies the type (NOP, Query...)
1602  * @timeout - time in seconds
1603  *
1604  * NOTE: Since there is only one available tag for device management commands,
1605  * it is expected you hold the hba->dev_cmd.lock mutex.
1606  */
1607 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1608                 enum dev_cmd_type cmd_type, int timeout)
1609 {
1610         struct ufshcd_lrb *lrbp;
1611         int err;
1612         int tag;
1613         struct completion wait;
1614         unsigned long flags;
1615
1616         /*
1617          * Get free slot, sleep if slots are unavailable.
1618          * Even though we use wait_event() which sleeps indefinitely,
1619          * the maximum wait time is bounded by SCSI request timeout.
1620          */
1621         wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1622
1623         init_completion(&wait);
1624         lrbp = &hba->lrb[tag];
1625         WARN_ON(lrbp->cmd);
1626         err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1627         if (unlikely(err))
1628                 goto out_put_tag;
1629
1630         hba->dev_cmd.complete = &wait;
1631
1632         /* Make sure descriptors are ready before ringing the doorbell */
1633         wmb();
1634         spin_lock_irqsave(hba->host->host_lock, flags);
1635         ufshcd_send_command(hba, tag);
1636         spin_unlock_irqrestore(hba->host->host_lock, flags);
1637
1638         err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1639
1640 out_put_tag:
1641         ufshcd_put_dev_cmd_tag(hba, tag);
1642         wake_up(&hba->dev_cmd.tag_wq);
1643         return err;
1644 }
1645
1646 /**
1647  * ufshcd_init_query() - init the query response and request parameters
1648  * @hba: per-adapter instance
1649  * @request: address of the request pointer to be initialized
1650  * @response: address of the response pointer to be initialized
1651  * @opcode: operation to perform
1652  * @idn: flag idn to access
1653  * @index: LU number to access
1654  * @selector: query/flag/descriptor further identification
1655  */
1656 static inline void ufshcd_init_query(struct ufs_hba *hba,
1657                 struct ufs_query_req **request, struct ufs_query_res **response,
1658                 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1659 {
1660         *request = &hba->dev_cmd.query.request;
1661         *response = &hba->dev_cmd.query.response;
1662         memset(*request, 0, sizeof(struct ufs_query_req));
1663         memset(*response, 0, sizeof(struct ufs_query_res));
1664         (*request)->upiu_req.opcode = opcode;
1665         (*request)->upiu_req.idn = idn;
1666         (*request)->upiu_req.index = index;
1667         (*request)->upiu_req.selector = selector;
1668 }
1669
1670 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1671         enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1672 {
1673         int ret;
1674         int retries;
1675
1676         for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1677                 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1678                 if (ret)
1679                         dev_dbg(hba->dev,
1680                                 "%s: failed with error %d, retries %d\n",
1681                                 __func__, ret, retries);
1682                 else
1683                         break;
1684         }
1685
1686         if (ret)
1687                 dev_err(hba->dev,
1688                         "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1689                         __func__, opcode, idn, ret, retries);
1690         return ret;
1691 }
1692
1693 /**
1694  * ufshcd_query_flag() - API function for sending flag query requests
1695  * hba: per-adapter instance
1696  * query_opcode: flag query to perform
1697  * idn: flag idn to access
1698  * flag_res: the flag value after the query request completes
1699  *
1700  * Returns 0 for success, non-zero in case of failure
1701  */
1702 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1703                         enum flag_idn idn, bool *flag_res)
1704 {
1705         struct ufs_query_req *request = NULL;
1706         struct ufs_query_res *response = NULL;
1707         int err, index = 0, selector = 0;
1708         int timeout = QUERY_REQ_TIMEOUT;
1709
1710         BUG_ON(!hba);
1711
1712         ufshcd_hold(hba, false);
1713         mutex_lock(&hba->dev_cmd.lock);
1714         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1715                         selector);
1716
1717         switch (opcode) {
1718         case UPIU_QUERY_OPCODE_SET_FLAG:
1719         case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1720         case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1721                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1722                 break;
1723         case UPIU_QUERY_OPCODE_READ_FLAG:
1724                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1725                 if (!flag_res) {
1726                         /* No dummy reads */
1727                         dev_err(hba->dev, "%s: Invalid argument for read request\n",
1728                                         __func__);
1729                         err = -EINVAL;
1730                         goto out_unlock;
1731                 }
1732                 break;
1733         default:
1734                 dev_err(hba->dev,
1735                         "%s: Expected query flag opcode but got = %d\n",
1736                         __func__, opcode);
1737                 err = -EINVAL;
1738                 goto out_unlock;
1739         }
1740
1741         if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1742                 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1743
1744         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
1745
1746         if (err) {
1747                 dev_err(hba->dev,
1748                         "%s: Sending flag query for idn %d failed, err = %d\n",
1749                         __func__, idn, err);
1750                 goto out_unlock;
1751         }
1752
1753         if (flag_res)
1754                 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1755                                 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1756
1757 out_unlock:
1758         mutex_unlock(&hba->dev_cmd.lock);
1759         ufshcd_release(hba);
1760         return err;
1761 }
1762
1763 /**
1764  * ufshcd_query_attr - API function for sending attribute requests
1765  * hba: per-adapter instance
1766  * opcode: attribute opcode
1767  * idn: attribute idn to access
1768  * index: index field
1769  * selector: selector field
1770  * attr_val: the attribute value after the query request completes
1771  *
1772  * Returns 0 for success, non-zero in case of failure
1773 */
1774 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1775                         enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1776 {
1777         struct ufs_query_req *request = NULL;
1778         struct ufs_query_res *response = NULL;
1779         int err;
1780
1781         BUG_ON(!hba);
1782
1783         ufshcd_hold(hba, false);
1784         if (!attr_val) {
1785                 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1786                                 __func__, opcode);
1787                 err = -EINVAL;
1788                 goto out;
1789         }
1790
1791         mutex_lock(&hba->dev_cmd.lock);
1792         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1793                         selector);
1794
1795         switch (opcode) {
1796         case UPIU_QUERY_OPCODE_WRITE_ATTR:
1797                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1798                 request->upiu_req.value = cpu_to_be32(*attr_val);
1799                 break;
1800         case UPIU_QUERY_OPCODE_READ_ATTR:
1801                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1802                 break;
1803         default:
1804                 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1805                                 __func__, opcode);
1806                 err = -EINVAL;
1807                 goto out_unlock;
1808         }
1809
1810         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1811
1812         if (err) {
1813                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1814                                 __func__, opcode, idn, err);
1815                 goto out_unlock;
1816         }
1817
1818         *attr_val = be32_to_cpu(response->upiu_res.value);
1819
1820 out_unlock:
1821         mutex_unlock(&hba->dev_cmd.lock);
1822 out:
1823         ufshcd_release(hba);
1824         return err;
1825 }
1826
1827 /**
1828  * ufshcd_query_attr_retry() - API function for sending query
1829  * attribute with retries
1830  * @hba: per-adapter instance
1831  * @opcode: attribute opcode
1832  * @idn: attribute idn to access
1833  * @index: index field
1834  * @selector: selector field
1835  * @attr_val: the attribute value after the query request
1836  * completes
1837  *
1838  * Returns 0 for success, non-zero in case of failure
1839 */
1840 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1841         enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1842         u32 *attr_val)
1843 {
1844         int ret = 0;
1845         u32 retries;
1846
1847          for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1848                 ret = ufshcd_query_attr(hba, opcode, idn, index,
1849                                                 selector, attr_val);
1850                 if (ret)
1851                         dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1852                                 __func__, ret, retries);
1853                 else
1854                         break;
1855         }
1856
1857         if (ret)
1858                 dev_err(hba->dev,
1859                         "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1860                         __func__, idn, ret, QUERY_REQ_RETRIES);
1861         return ret;
1862 }
1863
1864 /**
1865  * ufshcd_query_descriptor - API function for sending descriptor requests
1866  * hba: per-adapter instance
1867  * opcode: attribute opcode
1868  * idn: attribute idn to access
1869  * index: index field
1870  * selector: selector field
1871  * desc_buf: the buffer that contains the descriptor
1872  * buf_len: length parameter passed to the device
1873  *
1874  * Returns 0 for success, non-zero in case of failure.
1875  * The buf_len parameter will contain, on return, the length parameter
1876  * received on the response.
1877  */
1878 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1879                         enum query_opcode opcode, enum desc_idn idn, u8 index,
1880                         u8 selector, u8 *desc_buf, int *buf_len)
1881 {
1882         struct ufs_query_req *request = NULL;
1883         struct ufs_query_res *response = NULL;
1884         int err;
1885
1886         BUG_ON(!hba);
1887
1888         ufshcd_hold(hba, false);
1889         if (!desc_buf) {
1890                 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1891                                 __func__, opcode);
1892                 err = -EINVAL;
1893                 goto out;
1894         }
1895
1896         if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1897                 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1898                                 __func__, *buf_len);
1899                 err = -EINVAL;
1900                 goto out;
1901         }
1902
1903         mutex_lock(&hba->dev_cmd.lock);
1904         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1905                         selector);
1906         hba->dev_cmd.query.descriptor = desc_buf;
1907         request->upiu_req.length = cpu_to_be16(*buf_len);
1908
1909         switch (opcode) {
1910         case UPIU_QUERY_OPCODE_WRITE_DESC:
1911                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1912                 break;
1913         case UPIU_QUERY_OPCODE_READ_DESC:
1914                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1915                 break;
1916         default:
1917                 dev_err(hba->dev,
1918                                 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1919                                 __func__, opcode);
1920                 err = -EINVAL;
1921                 goto out_unlock;
1922         }
1923
1924         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1925
1926         if (err) {
1927                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1928                                 __func__, opcode, idn, err);
1929                 goto out_unlock;
1930         }
1931
1932         hba->dev_cmd.query.descriptor = NULL;
1933         *buf_len = be16_to_cpu(response->upiu_res.length);
1934
1935 out_unlock:
1936         mutex_unlock(&hba->dev_cmd.lock);
1937 out:
1938         ufshcd_release(hba);
1939         return err;
1940 }
1941
1942 /**
1943  * ufshcd_read_desc_param - read the specified descriptor parameter
1944  * @hba: Pointer to adapter instance
1945  * @desc_id: descriptor idn value
1946  * @desc_index: descriptor index
1947  * @param_offset: offset of the parameter to read
1948  * @param_read_buf: pointer to buffer where parameter would be read
1949  * @param_size: sizeof(param_read_buf)
1950  *
1951  * Return 0 in case of success, non-zero otherwise
1952  */
1953 static int ufshcd_read_desc_param(struct ufs_hba *hba,
1954                                   enum desc_idn desc_id,
1955                                   int desc_index,
1956                                   u32 param_offset,
1957                                   u8 *param_read_buf,
1958                                   u32 param_size)
1959 {
1960         int ret;
1961         u8 *desc_buf;
1962         u32 buff_len;
1963         bool is_kmalloc = true;
1964
1965         /* safety checks */
1966         if (desc_id >= QUERY_DESC_IDN_MAX)
1967                 return -EINVAL;
1968
1969         buff_len = ufs_query_desc_max_size[desc_id];
1970         if ((param_offset + param_size) > buff_len)
1971                 return -EINVAL;
1972
1973         if (!param_offset && (param_size == buff_len)) {
1974                 /* memory space already available to hold full descriptor */
1975                 desc_buf = param_read_buf;
1976                 is_kmalloc = false;
1977         } else {
1978                 /* allocate memory to hold full descriptor */
1979                 desc_buf = kmalloc(buff_len, GFP_KERNEL);
1980                 if (!desc_buf)
1981                         return -ENOMEM;
1982         }
1983
1984         ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
1985                                       desc_id, desc_index, 0, desc_buf,
1986                                       &buff_len);
1987
1988         if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
1989             (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
1990              ufs_query_desc_max_size[desc_id])
1991             || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
1992                 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
1993                         __func__, desc_id, param_offset, buff_len, ret);
1994                 if (!ret)
1995                         ret = -EINVAL;
1996
1997                 goto out;
1998         }
1999
2000         if (is_kmalloc)
2001                 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2002 out:
2003         if (is_kmalloc)
2004                 kfree(desc_buf);
2005         return ret;
2006 }
2007
2008 static inline int ufshcd_read_desc(struct ufs_hba *hba,
2009                                    enum desc_idn desc_id,
2010                                    int desc_index,
2011                                    u8 *buf,
2012                                    u32 size)
2013 {
2014         return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2015 }
2016
2017 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2018                                          u8 *buf,
2019                                          u32 size)
2020 {
2021         return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2022 }
2023
2024 /**
2025  * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2026  * @hba: Pointer to adapter instance
2027  * @lun: lun id
2028  * @param_offset: offset of the parameter to read
2029  * @param_read_buf: pointer to buffer where parameter would be read
2030  * @param_size: sizeof(param_read_buf)
2031  *
2032  * Return 0 in case of success, non-zero otherwise
2033  */
2034 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2035                                               int lun,
2036                                               enum unit_desc_param param_offset,
2037                                               u8 *param_read_buf,
2038                                               u32 param_size)
2039 {
2040         /*
2041          * Unit descriptors are only available for general purpose LUs (LUN id
2042          * from 0 to 7) and RPMB Well known LU.
2043          */
2044         if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
2045                 return -EOPNOTSUPP;
2046
2047         return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2048                                       param_offset, param_read_buf, param_size);
2049 }
2050
2051 /**
2052  * ufshcd_memory_alloc - allocate memory for host memory space data structures
2053  * @hba: per adapter instance
2054  *
2055  * 1. Allocate DMA memory for Command Descriptor array
2056  *      Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2057  * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2058  * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2059  *      (UTMRDL)
2060  * 4. Allocate memory for local reference block(lrb).
2061  *
2062  * Returns 0 for success, non-zero in case of failure
2063  */
2064 static int ufshcd_memory_alloc(struct ufs_hba *hba)
2065 {
2066         size_t utmrdl_size, utrdl_size, ucdl_size;
2067
2068         /* Allocate memory for UTP command descriptors */
2069         ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2070         hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2071                                                   ucdl_size,
2072                                                   &hba->ucdl_dma_addr,
2073                                                   GFP_KERNEL);
2074
2075         /*
2076          * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2077          * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2078          * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2079          * be aligned to 128 bytes as well
2080          */
2081         if (!hba->ucdl_base_addr ||
2082             WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
2083                 dev_err(hba->dev,
2084                         "Command Descriptor Memory allocation failed\n");
2085                 goto out;
2086         }
2087
2088         /*
2089          * Allocate memory for UTP Transfer descriptors
2090          * UFSHCI requires 1024 byte alignment of UTRD
2091          */
2092         utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2093         hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2094                                                    utrdl_size,
2095                                                    &hba->utrdl_dma_addr,
2096                                                    GFP_KERNEL);
2097         if (!hba->utrdl_base_addr ||
2098             WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
2099                 dev_err(hba->dev,
2100                         "Transfer Descriptor Memory allocation failed\n");
2101                 goto out;
2102         }
2103
2104         /*
2105          * Allocate memory for UTP Task Management descriptors
2106          * UFSHCI requires 1024 byte alignment of UTMRD
2107          */
2108         utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2109         hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2110                                                     utmrdl_size,
2111                                                     &hba->utmrdl_dma_addr,
2112                                                     GFP_KERNEL);
2113         if (!hba->utmrdl_base_addr ||
2114             WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
2115                 dev_err(hba->dev,
2116                 "Task Management Descriptor Memory allocation failed\n");
2117                 goto out;
2118         }
2119
2120         /* Allocate memory for local reference block */
2121         hba->lrb = devm_kzalloc(hba->dev,
2122                                 hba->nutrs * sizeof(struct ufshcd_lrb),
2123                                 GFP_KERNEL);
2124         if (!hba->lrb) {
2125                 dev_err(hba->dev, "LRB Memory allocation failed\n");
2126                 goto out;
2127         }
2128         return 0;
2129 out:
2130         return -ENOMEM;
2131 }
2132
2133 /**
2134  * ufshcd_host_memory_configure - configure local reference block with
2135  *                              memory offsets
2136  * @hba: per adapter instance
2137  *
2138  * Configure Host memory space
2139  * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2140  * address.
2141  * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2142  * and PRDT offset.
2143  * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2144  * into local reference block.
2145  */
2146 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2147 {
2148         struct utp_transfer_cmd_desc *cmd_descp;
2149         struct utp_transfer_req_desc *utrdlp;
2150         dma_addr_t cmd_desc_dma_addr;
2151         dma_addr_t cmd_desc_element_addr;
2152         u16 response_offset;
2153         u16 prdt_offset;
2154         int cmd_desc_size;
2155         int i;
2156
2157         utrdlp = hba->utrdl_base_addr;
2158         cmd_descp = hba->ucdl_base_addr;
2159
2160         response_offset =
2161                 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2162         prdt_offset =
2163                 offsetof(struct utp_transfer_cmd_desc, prd_table);
2164
2165         cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2166         cmd_desc_dma_addr = hba->ucdl_dma_addr;
2167
2168         for (i = 0; i < hba->nutrs; i++) {
2169                 /* Configure UTRD with command descriptor base address */
2170                 cmd_desc_element_addr =
2171                                 (cmd_desc_dma_addr + (cmd_desc_size * i));
2172                 utrdlp[i].command_desc_base_addr_lo =
2173                                 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2174                 utrdlp[i].command_desc_base_addr_hi =
2175                                 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2176
2177                 /* Response upiu and prdt offset should be in double words */
2178                 utrdlp[i].response_upiu_offset =
2179                                 cpu_to_le16((response_offset >> 2));
2180                 utrdlp[i].prd_table_offset =
2181                                 cpu_to_le16((prdt_offset >> 2));
2182                 utrdlp[i].response_upiu_length =
2183                                 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2184
2185                 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2186                 hba->lrb[i].ucd_req_ptr =
2187                         (struct utp_upiu_req *)(cmd_descp + i);
2188                 hba->lrb[i].ucd_rsp_ptr =
2189                         (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2190                 hba->lrb[i].ucd_prdt_ptr =
2191                         (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2192         }
2193 }
2194
2195 /**
2196  * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2197  * @hba: per adapter instance
2198  *
2199  * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2200  * in order to initialize the Unipro link startup procedure.
2201  * Once the Unipro links are up, the device connected to the controller
2202  * is detected.
2203  *
2204  * Returns 0 on success, non-zero value on failure
2205  */
2206 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2207 {
2208         struct uic_command uic_cmd = {0};
2209         int ret;
2210
2211         uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2212
2213         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2214         if (ret)
2215                 dev_err(hba->dev,
2216                         "dme-link-startup: error code %d\n", ret);
2217         return ret;
2218 }
2219
2220 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2221 {
2222         #define MIN_DELAY_BEFORE_DME_CMDS_US    1000
2223         unsigned long min_sleep_time_us;
2224
2225         if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2226                 return;
2227
2228         /*
2229          * last_dme_cmd_tstamp will be 0 only for 1st call to
2230          * this function
2231          */
2232         if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2233                 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2234         } else {
2235                 unsigned long delta =
2236                         (unsigned long) ktime_to_us(
2237                                 ktime_sub(ktime_get(),
2238                                 hba->last_dme_cmd_tstamp));
2239
2240                 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2241                         min_sleep_time_us =
2242                                 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2243                 else
2244                         return; /* no more delay required */
2245         }
2246
2247         /* allow sleep for extra 50us if needed */
2248         usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2249 }
2250
2251 /**
2252  * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2253  * @hba: per adapter instance
2254  * @attr_sel: uic command argument1
2255  * @attr_set: attribute set type as uic command argument2
2256  * @mib_val: setting value as uic command argument3
2257  * @peer: indicate whether peer or local
2258  *
2259  * Returns 0 on success, non-zero value on failure
2260  */
2261 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2262                         u8 attr_set, u32 mib_val, u8 peer)
2263 {
2264         struct uic_command uic_cmd = {0};
2265         static const char *const action[] = {
2266                 "dme-set",
2267                 "dme-peer-set"
2268         };
2269         const char *set = action[!!peer];
2270         int ret;
2271         int retries = UFS_UIC_COMMAND_RETRIES;
2272
2273         uic_cmd.command = peer ?
2274                 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2275         uic_cmd.argument1 = attr_sel;
2276         uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2277         uic_cmd.argument3 = mib_val;
2278
2279         do {
2280                 /* for peer attributes we retry upon failure */
2281                 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2282                 if (ret)
2283                         dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2284                                 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2285         } while (ret && peer && --retries);
2286
2287         if (!retries)
2288                 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2289                                 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2290                                 retries);
2291
2292         return ret;
2293 }
2294 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2295
2296 /**
2297  * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2298  * @hba: per adapter instance
2299  * @attr_sel: uic command argument1
2300  * @mib_val: the value of the attribute as returned by the UIC command
2301  * @peer: indicate whether peer or local
2302  *
2303  * Returns 0 on success, non-zero value on failure
2304  */
2305 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2306                         u32 *mib_val, u8 peer)
2307 {
2308         struct uic_command uic_cmd = {0};
2309         static const char *const action[] = {
2310                 "dme-get",
2311                 "dme-peer-get"
2312         };
2313         const char *get = action[!!peer];
2314         int ret;
2315         int retries = UFS_UIC_COMMAND_RETRIES;
2316         struct ufs_pa_layer_attr orig_pwr_info;
2317         struct ufs_pa_layer_attr temp_pwr_info;
2318         bool pwr_mode_change = false;
2319
2320         if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2321                 orig_pwr_info = hba->pwr_info;
2322                 temp_pwr_info = orig_pwr_info;
2323
2324                 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2325                     orig_pwr_info.pwr_rx == FAST_MODE) {
2326                         temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2327                         temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2328                         pwr_mode_change = true;
2329                 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2330                     orig_pwr_info.pwr_rx == SLOW_MODE) {
2331                         temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2332                         temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2333                         pwr_mode_change = true;
2334                 }
2335                 if (pwr_mode_change) {
2336                         ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2337                         if (ret)
2338                                 goto out;
2339                 }
2340         }
2341
2342         uic_cmd.command = peer ?
2343                 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2344         uic_cmd.argument1 = attr_sel;
2345
2346         do {
2347                 /* for peer attributes we retry upon failure */
2348                 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2349                 if (ret)
2350                         dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2351                                 get, UIC_GET_ATTR_ID(attr_sel), ret);
2352         } while (ret && peer && --retries);
2353
2354         if (!retries)
2355                 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2356                                 get, UIC_GET_ATTR_ID(attr_sel), retries);
2357
2358         if (mib_val && !ret)
2359                 *mib_val = uic_cmd.argument3;
2360
2361         if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2362             && pwr_mode_change)
2363                 ufshcd_change_power_mode(hba, &orig_pwr_info);
2364 out:
2365         return ret;
2366 }
2367 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2368
2369 /**
2370  * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2371  * state) and waits for it to take effect.
2372  *
2373  * @hba: per adapter instance
2374  * @cmd: UIC command to execute
2375  *
2376  * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2377  * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2378  * and device UniPro link and hence it's final completion would be indicated by
2379  * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2380  * addition to normal UIC command completion Status (UCCS). This function only
2381  * returns after the relevant status bits indicate the completion.
2382  *
2383  * Returns 0 on success, non-zero value on failure
2384  */
2385 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2386 {
2387         struct completion uic_async_done;
2388         unsigned long flags;
2389         u8 status;
2390         int ret;
2391         bool reenable_intr = false;
2392
2393         mutex_lock(&hba->uic_cmd_mutex);
2394         init_completion(&uic_async_done);
2395         ufshcd_add_delay_before_dme_cmd(hba);
2396
2397         spin_lock_irqsave(hba->host->host_lock, flags);
2398         hba->uic_async_done = &uic_async_done;
2399         if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2400                 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2401                 /*
2402                  * Make sure UIC command completion interrupt is disabled before
2403                  * issuing UIC command.
2404                  */
2405                 wmb();
2406                 reenable_intr = true;
2407         }
2408         ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2409         spin_unlock_irqrestore(hba->host->host_lock, flags);
2410         if (ret) {
2411                 dev_err(hba->dev,
2412                         "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2413                         cmd->command, cmd->argument3, ret);
2414                 goto out;
2415         }
2416
2417         if (!wait_for_completion_timeout(hba->uic_async_done,
2418                                          msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2419                 dev_err(hba->dev,
2420                         "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2421                         cmd->command, cmd->argument3);
2422                 ret = -ETIMEDOUT;
2423                 goto out;
2424         }
2425
2426         status = ufshcd_get_upmcrs(hba);
2427         if (status != PWR_LOCAL) {
2428                 dev_err(hba->dev,
2429                         "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2430                         cmd->command, status);
2431                 ret = (status != PWR_OK) ? status : -1;
2432         }
2433 out:
2434         spin_lock_irqsave(hba->host->host_lock, flags);
2435         hba->active_uic_cmd = NULL;
2436         hba->uic_async_done = NULL;
2437         if (reenable_intr)
2438                 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2439         spin_unlock_irqrestore(hba->host->host_lock, flags);
2440         mutex_unlock(&hba->uic_cmd_mutex);
2441
2442         return ret;
2443 }
2444
2445 /**
2446  * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2447  *                              using DME_SET primitives.
2448  * @hba: per adapter instance
2449  * @mode: powr mode value
2450  *
2451  * Returns 0 on success, non-zero value on failure
2452  */
2453 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2454 {
2455         struct uic_command uic_cmd = {0};
2456         int ret;
2457
2458         if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2459                 ret = ufshcd_dme_set(hba,
2460                                 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2461                 if (ret) {
2462                         dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2463                                                 __func__, ret);
2464                         goto out;
2465                 }
2466         }
2467
2468         uic_cmd.command = UIC_CMD_DME_SET;
2469         uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2470         uic_cmd.argument3 = mode;
2471         ufshcd_hold(hba, false);
2472         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2473         ufshcd_release(hba);
2474
2475 out:
2476         return ret;
2477 }
2478
2479 static int ufshcd_link_recovery(struct ufs_hba *hba)
2480 {
2481         int ret;
2482         unsigned long flags;
2483
2484         spin_lock_irqsave(hba->host->host_lock, flags);
2485         hba->ufshcd_state = UFSHCD_STATE_RESET;
2486         ufshcd_set_eh_in_progress(hba);
2487         spin_unlock_irqrestore(hba->host->host_lock, flags);
2488
2489         ret = ufshcd_host_reset_and_restore(hba);
2490
2491         spin_lock_irqsave(hba->host->host_lock, flags);
2492         if (ret)
2493                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2494         ufshcd_clear_eh_in_progress(hba);
2495         spin_unlock_irqrestore(hba->host->host_lock, flags);
2496
2497         if (ret)
2498                 dev_err(hba->dev, "%s: link recovery failed, err %d",
2499                         __func__, ret);
2500
2501         return ret;
2502 }
2503
2504 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2505 {
2506         int ret;
2507         struct uic_command uic_cmd = {0};
2508
2509         uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2510         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2511
2512         if (ret) {
2513                 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2514                         __func__, ret);
2515
2516                 /*
2517                  * If link recovery fails then return error so that caller
2518                  * don't retry the hibern8 enter again.
2519                  */
2520                 if (ufshcd_link_recovery(hba))
2521                         ret = -ENOLINK;
2522         }
2523
2524         return ret;
2525 }
2526
2527 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2528 {
2529         int ret = 0, retries;
2530
2531         for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2532                 ret = __ufshcd_uic_hibern8_enter(hba);
2533                 if (!ret || ret == -ENOLINK)
2534                         goto out;
2535         }
2536 out:
2537         return ret;
2538 }
2539
2540 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2541 {
2542         struct uic_command uic_cmd = {0};
2543         int ret;
2544
2545         uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2546         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2547         if (ret) {
2548                 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2549                         __func__, ret);
2550                 ret = ufshcd_link_recovery(hba);
2551         }
2552
2553         return ret;
2554 }
2555
2556  /**
2557  * ufshcd_init_pwr_info - setting the POR (power on reset)
2558  * values in hba power info
2559  * @hba: per-adapter instance
2560  */
2561 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2562 {
2563         hba->pwr_info.gear_rx = UFS_PWM_G1;
2564         hba->pwr_info.gear_tx = UFS_PWM_G1;
2565         hba->pwr_info.lane_rx = 1;
2566         hba->pwr_info.lane_tx = 1;
2567         hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2568         hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2569         hba->pwr_info.hs_rate = 0;
2570 }
2571
2572 /**
2573  * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2574  * @hba: per-adapter instance
2575  */
2576 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2577 {
2578         struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2579
2580         if (hba->max_pwr_info.is_valid)
2581                 return 0;
2582
2583         pwr_info->pwr_tx = FASTAUTO_MODE;
2584         pwr_info->pwr_rx = FASTAUTO_MODE;
2585         pwr_info->hs_rate = PA_HS_MODE_B;
2586
2587         /* Get the connected lane count */
2588         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2589                         &pwr_info->lane_rx);
2590         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2591                         &pwr_info->lane_tx);
2592
2593         if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2594                 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2595                                 __func__,
2596                                 pwr_info->lane_rx,
2597                                 pwr_info->lane_tx);
2598                 return -EINVAL;
2599         }
2600
2601         /*
2602          * First, get the maximum gears of HS speed.
2603          * If a zero value, it means there is no HSGEAR capability.
2604          * Then, get the maximum gears of PWM speed.
2605          */
2606         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2607         if (!pwr_info->gear_rx) {
2608                 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2609                                 &pwr_info->gear_rx);
2610                 if (!pwr_info->gear_rx) {
2611                         dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2612                                 __func__, pwr_info->gear_rx);
2613                         return -EINVAL;
2614                 }
2615                 pwr_info->pwr_rx = SLOWAUTO_MODE;
2616         }
2617
2618         ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2619                         &pwr_info->gear_tx);
2620         if (!pwr_info->gear_tx) {
2621                 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2622                                 &pwr_info->gear_tx);
2623                 if (!pwr_info->gear_tx) {
2624                         dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2625                                 __func__, pwr_info->gear_tx);
2626                         return -EINVAL;
2627                 }
2628                 pwr_info->pwr_tx = SLOWAUTO_MODE;
2629         }
2630
2631         hba->max_pwr_info.is_valid = true;
2632         return 0;
2633 }
2634
2635 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2636                              struct ufs_pa_layer_attr *pwr_mode)
2637 {
2638         int ret;
2639
2640         /* if already configured to the requested pwr_mode */
2641         if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2642             pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2643             pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2644             pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2645             pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2646             pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2647             pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2648                 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2649                 return 0;
2650         }
2651
2652         /*
2653          * Configure attributes for power mode change with below.
2654          * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2655          * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2656          * - PA_HSSERIES
2657          */
2658         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2659         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2660                         pwr_mode->lane_rx);
2661         if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2662                         pwr_mode->pwr_rx == FAST_MODE)
2663                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2664         else
2665                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2666
2667         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2668         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2669                         pwr_mode->lane_tx);
2670         if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2671                         pwr_mode->pwr_tx == FAST_MODE)
2672                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2673         else
2674                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2675
2676         if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2677             pwr_mode->pwr_tx == FASTAUTO_MODE ||
2678             pwr_mode->pwr_rx == FAST_MODE ||
2679             pwr_mode->pwr_tx == FAST_MODE)
2680                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2681                                                 pwr_mode->hs_rate);
2682
2683         ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2684                         | pwr_mode->pwr_tx);
2685
2686         if (ret) {
2687                 dev_err(hba->dev,
2688                         "%s: power mode change failed %d\n", __func__, ret);
2689         } else {
2690                 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2691                                                                 pwr_mode);
2692
2693                 memcpy(&hba->pwr_info, pwr_mode,
2694                         sizeof(struct ufs_pa_layer_attr));
2695         }
2696
2697         return ret;
2698 }
2699
2700 /**
2701  * ufshcd_config_pwr_mode - configure a new power mode
2702  * @hba: per-adapter instance
2703  * @desired_pwr_mode: desired power configuration
2704  */
2705 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2706                 struct ufs_pa_layer_attr *desired_pwr_mode)
2707 {
2708         struct ufs_pa_layer_attr final_params = { 0 };
2709         int ret;
2710
2711         ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2712                                         desired_pwr_mode, &final_params);
2713
2714         if (ret)
2715                 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2716
2717         ret = ufshcd_change_power_mode(hba, &final_params);
2718
2719         return ret;
2720 }
2721
2722 /**
2723  * ufshcd_complete_dev_init() - checks device readiness
2724  * hba: per-adapter instance
2725  *
2726  * Set fDeviceInit flag and poll until device toggles it.
2727  */
2728 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2729 {
2730         int i;
2731         int err;
2732         bool flag_res = 1;
2733
2734         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2735                 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2736         if (err) {
2737                 dev_err(hba->dev,
2738                         "%s setting fDeviceInit flag failed with error %d\n",
2739                         __func__, err);
2740                 goto out;
2741         }
2742
2743         /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2744         for (i = 0; i < 1000 && !err && flag_res; i++)
2745                 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2746                         QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2747
2748         if (err)
2749                 dev_err(hba->dev,
2750                         "%s reading fDeviceInit flag failed with error %d\n",
2751                         __func__, err);
2752         else if (flag_res)
2753                 dev_err(hba->dev,
2754                         "%s fDeviceInit was not cleared by the device\n",
2755                         __func__);
2756
2757 out:
2758         return err;
2759 }
2760
2761 /**
2762  * ufshcd_make_hba_operational - Make UFS controller operational
2763  * @hba: per adapter instance
2764  *
2765  * To bring UFS host controller to operational state,
2766  * 1. Enable required interrupts
2767  * 2. Configure interrupt aggregation
2768  * 3. Program UTRL and UTMRL base address
2769  * 4. Configure run-stop-registers
2770  *
2771  * Returns 0 on success, non-zero value on failure
2772  */
2773 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2774 {
2775         int err = 0;
2776         u32 reg;
2777
2778         /* Enable required interrupts */
2779         ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2780
2781         /* Configure interrupt aggregation */
2782         if (ufshcd_is_intr_aggr_allowed(hba))
2783                 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2784         else
2785                 ufshcd_disable_intr_aggr(hba);
2786
2787         /* Configure UTRL and UTMRL base address registers */
2788         ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2789                         REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2790         ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2791                         REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2792         ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2793                         REG_UTP_TASK_REQ_LIST_BASE_L);
2794         ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2795                         REG_UTP_TASK_REQ_LIST_BASE_H);
2796
2797         /*
2798          * Make sure base address and interrupt setup are updated before
2799          * enabling the run/stop registers below.
2800          */
2801         wmb();
2802
2803         /*
2804          * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2805          */
2806         reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2807         if (!(ufshcd_get_lists_status(reg))) {
2808                 ufshcd_enable_run_stop_reg(hba);
2809         } else {
2810                 dev_err(hba->dev,
2811                         "Host controller not ready to process requests");
2812                 err = -EIO;
2813                 goto out;
2814         }
2815
2816 out:
2817         return err;
2818 }
2819
2820 /**
2821  * ufshcd_hba_stop - Send controller to reset state
2822  * @hba: per adapter instance
2823  * @can_sleep: perform sleep or just spin
2824  */
2825 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
2826 {
2827         int err;
2828
2829         ufshcd_writel(hba, CONTROLLER_DISABLE,  REG_CONTROLLER_ENABLE);
2830         err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
2831                                         CONTROLLER_ENABLE, CONTROLLER_DISABLE,
2832                                         10, 1, can_sleep);
2833         if (err)
2834                 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
2835 }
2836
2837 /**
2838  * ufshcd_hba_enable - initialize the controller
2839  * @hba: per adapter instance
2840  *
2841  * The controller resets itself and controller firmware initialization
2842  * sequence kicks off. When controller is ready it will set
2843  * the Host Controller Enable bit to 1.
2844  *
2845  * Returns 0 on success, non-zero value on failure
2846  */
2847 static int ufshcd_hba_enable(struct ufs_hba *hba)
2848 {
2849         int retry;
2850
2851         /*
2852          * msleep of 1 and 5 used in this function might result in msleep(20),
2853          * but it was necessary to send the UFS FPGA to reset mode during
2854          * development and testing of this driver. msleep can be changed to
2855          * mdelay and retry count can be reduced based on the controller.
2856          */
2857         if (!ufshcd_is_hba_active(hba))
2858                 /* change controller state to "reset state" */
2859                 ufshcd_hba_stop(hba, true);
2860
2861         /* UniPro link is disabled at this point */
2862         ufshcd_set_link_off(hba);
2863
2864         ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
2865
2866         /* start controller initialization sequence */
2867         ufshcd_hba_start(hba);
2868
2869         /*
2870          * To initialize a UFS host controller HCE bit must be set to 1.
2871          * During initialization the HCE bit value changes from 1->0->1.
2872          * When the host controller completes initialization sequence
2873          * it sets the value of HCE bit to 1. The same HCE bit is read back
2874          * to check if the controller has completed initialization sequence.
2875          * So without this delay the value HCE = 1, set in the previous
2876          * instruction might be read back.
2877          * This delay can be changed based on the controller.
2878          */
2879         msleep(1);
2880
2881         /* wait for the host controller to complete initialization */
2882         retry = 10;
2883         while (ufshcd_is_hba_active(hba)) {
2884                 if (retry) {
2885                         retry--;
2886                 } else {
2887                         dev_err(hba->dev,
2888                                 "Controller enable failed\n");
2889                         return -EIO;
2890                 }
2891                 msleep(5);
2892         }
2893
2894         /* enable UIC related interrupts */
2895         ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
2896
2897         ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
2898
2899         return 0;
2900 }
2901
2902 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
2903 {
2904         int tx_lanes, i, err = 0;
2905
2906         if (!peer)
2907                 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2908                                &tx_lanes);
2909         else
2910                 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2911                                     &tx_lanes);
2912         for (i = 0; i < tx_lanes; i++) {
2913                 if (!peer)
2914                         err = ufshcd_dme_set(hba,
2915                                 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2916                                         UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2917                                         0);
2918                 else
2919                         err = ufshcd_dme_peer_set(hba,
2920                                 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
2921                                         UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
2922                                         0);
2923                 if (err) {
2924                         dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
2925                                 __func__, peer, i, err);
2926                         break;
2927                 }
2928         }
2929
2930         return err;
2931 }
2932
2933 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
2934 {
2935         return ufshcd_disable_tx_lcc(hba, true);
2936 }
2937
2938 /**
2939  * ufshcd_link_startup - Initialize unipro link startup
2940  * @hba: per adapter instance
2941  *
2942  * Returns 0 for success, non-zero in case of failure
2943  */
2944 static int ufshcd_link_startup(struct ufs_hba *hba)
2945 {
2946         int ret;
2947         int retries = DME_LINKSTARTUP_RETRIES;
2948
2949         do {
2950                 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
2951
2952                 ret = ufshcd_dme_link_startup(hba);
2953
2954                 /* check if device is detected by inter-connect layer */
2955                 if (!ret && !ufshcd_is_device_present(hba)) {
2956                         dev_err(hba->dev, "%s: Device not present\n", __func__);
2957                         ret = -ENXIO;
2958                         goto out;
2959                 }
2960
2961                 /*
2962                  * DME link lost indication is only received when link is up,
2963                  * but we can't be sure if the link is up until link startup
2964                  * succeeds. So reset the local Uni-Pro and try again.
2965                  */
2966                 if (ret && ufshcd_hba_enable(hba))
2967                         goto out;
2968         } while (ret && retries--);
2969
2970         if (ret)
2971                 /* failed to get the link up... retire */
2972                 goto out;
2973
2974         if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
2975                 ret = ufshcd_disable_device_tx_lcc(hba);
2976                 if (ret)
2977                         goto out;
2978         }
2979
2980         /* Include any host controller configuration via UIC commands */
2981         ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
2982         if (ret)
2983                 goto out;
2984
2985         ret = ufshcd_make_hba_operational(hba);
2986 out:
2987         if (ret)
2988                 dev_err(hba->dev, "link startup failed %d\n", ret);
2989         return ret;
2990 }
2991
2992 /**
2993  * ufshcd_verify_dev_init() - Verify device initialization
2994  * @hba: per-adapter instance
2995  *
2996  * Send NOP OUT UPIU and wait for NOP IN response to check whether the
2997  * device Transport Protocol (UTP) layer is ready after a reset.
2998  * If the UTP layer at the device side is not initialized, it may
2999  * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3000  * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3001  */
3002 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3003 {
3004         int err = 0;
3005         int retries;
3006
3007         ufshcd_hold(hba, false);
3008         mutex_lock(&hba->dev_cmd.lock);
3009         for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3010                 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3011                                                NOP_OUT_TIMEOUT);
3012
3013                 if (!err || err == -ETIMEDOUT)
3014                         break;
3015
3016                 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3017         }
3018         mutex_unlock(&hba->dev_cmd.lock);
3019         ufshcd_release(hba);
3020
3021         if (err)
3022                 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3023         return err;
3024 }
3025
3026 /**
3027  * ufshcd_set_queue_depth - set lun queue depth
3028  * @sdev: pointer to SCSI device
3029  *
3030  * Read bLUQueueDepth value and activate scsi tagged command
3031  * queueing. For WLUN, queue depth is set to 1. For best-effort
3032  * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3033  * value that host can queue.
3034  */
3035 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3036 {
3037         int ret = 0;
3038         u8 lun_qdepth;
3039         struct ufs_hba *hba;
3040
3041         hba = shost_priv(sdev->host);
3042
3043         lun_qdepth = hba->nutrs;
3044         ret = ufshcd_read_unit_desc_param(hba,
3045                                           ufshcd_scsi_to_upiu_lun(sdev->lun),
3046                                           UNIT_DESC_PARAM_LU_Q_DEPTH,
3047                                           &lun_qdepth,
3048                                           sizeof(lun_qdepth));
3049
3050         /* Some WLUN doesn't support unit descriptor */
3051         if (ret == -EOPNOTSUPP)
3052                 lun_qdepth = 1;
3053         else if (!lun_qdepth)
3054                 /* eventually, we can figure out the real queue depth */
3055                 lun_qdepth = hba->nutrs;
3056         else
3057                 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3058
3059         dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3060                         __func__, lun_qdepth);
3061         scsi_change_queue_depth(sdev, lun_qdepth);
3062 }
3063
3064 /*
3065  * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3066  * @hba: per-adapter instance
3067  * @lun: UFS device lun id
3068  * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3069  *
3070  * Returns 0 in case of success and b_lu_write_protect status would be returned
3071  * @b_lu_write_protect parameter.
3072  * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3073  * Returns -EINVAL in case of invalid parameters passed to this function.
3074  */
3075 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3076                             u8 lun,
3077                             u8 *b_lu_write_protect)
3078 {
3079         int ret;
3080
3081         if (!b_lu_write_protect)
3082                 ret = -EINVAL;
3083         /*
3084          * According to UFS device spec, RPMB LU can't be write
3085          * protected so skip reading bLUWriteProtect parameter for
3086          * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3087          */
3088         else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3089                 ret = -ENOTSUPP;
3090         else
3091                 ret = ufshcd_read_unit_desc_param(hba,
3092                                           lun,
3093                                           UNIT_DESC_PARAM_LU_WR_PROTECT,
3094                                           b_lu_write_protect,
3095                                           sizeof(*b_lu_write_protect));
3096         return ret;
3097 }
3098
3099 /**
3100  * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3101  * status
3102  * @hba: per-adapter instance
3103  * @sdev: pointer to SCSI device
3104  *
3105  */
3106 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3107                                                     struct scsi_device *sdev)
3108 {
3109         if (hba->dev_info.f_power_on_wp_en &&
3110             !hba->dev_info.is_lu_power_on_wp) {
3111                 u8 b_lu_write_protect;
3112
3113                 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3114                                       &b_lu_write_protect) &&
3115                     (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3116                         hba->dev_info.is_lu_power_on_wp = true;
3117         }
3118 }
3119
3120 /**
3121  * ufshcd_slave_alloc - handle initial SCSI device configurations
3122  * @sdev: pointer to SCSI device
3123  *
3124  * Returns success
3125  */
3126 static int ufshcd_slave_alloc(struct scsi_device *sdev)
3127 {
3128         struct ufs_hba *hba;
3129
3130         hba = shost_priv(sdev->host);
3131
3132         /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3133         sdev->use_10_for_ms = 1;
3134
3135         /* allow SCSI layer to restart the device in case of errors */
3136         sdev->allow_restart = 1;
3137
3138         /* REPORT SUPPORTED OPERATION CODES is not supported */
3139         sdev->no_report_opcodes = 1;
3140
3141
3142         ufshcd_set_queue_depth(sdev);
3143
3144         ufshcd_get_lu_power_on_wp_status(hba, sdev);
3145
3146         return 0;
3147 }
3148
3149 /**
3150  * ufshcd_change_queue_depth - change queue depth
3151  * @sdev: pointer to SCSI device
3152  * @depth: required depth to set
3153  *
3154  * Change queue depth and make sure the max. limits are not crossed.
3155  */
3156 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
3157 {
3158         struct ufs_hba *hba = shost_priv(sdev->host);
3159
3160         if (depth > hba->nutrs)
3161                 depth = hba->nutrs;
3162         return scsi_change_queue_depth(sdev, depth);
3163 }
3164
3165 /**
3166  * ufshcd_slave_configure - adjust SCSI device configurations
3167  * @sdev: pointer to SCSI device
3168  */
3169 static int ufshcd_slave_configure(struct scsi_device *sdev)
3170 {
3171         struct request_queue *q = sdev->request_queue;
3172
3173         blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3174         blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3175
3176         return 0;
3177 }
3178
3179 /**
3180  * ufshcd_slave_destroy - remove SCSI device configurations
3181  * @sdev: pointer to SCSI device
3182  */
3183 static void ufshcd_slave_destroy(struct scsi_device *sdev)
3184 {
3185         struct ufs_hba *hba;
3186
3187         hba = shost_priv(sdev->host);
3188         /* Drop the reference as it won't be needed anymore */
3189         if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3190                 unsigned long flags;
3191
3192                 spin_lock_irqsave(hba->host->host_lock, flags);
3193                 hba->sdev_ufs_device = NULL;
3194                 spin_unlock_irqrestore(hba->host->host_lock, flags);
3195         }
3196 }
3197
3198 /**
3199  * ufshcd_task_req_compl - handle task management request completion
3200  * @hba: per adapter instance
3201  * @index: index of the completed request
3202  * @resp: task management service response
3203  *
3204  * Returns non-zero value on error, zero on success
3205  */
3206 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3207 {
3208         struct utp_task_req_desc *task_req_descp;
3209         struct utp_upiu_task_rsp *task_rsp_upiup;
3210         unsigned long flags;
3211         int ocs_value;
3212         int task_result;
3213
3214         spin_lock_irqsave(hba->host->host_lock, flags);
3215
3216         /* Clear completed tasks from outstanding_tasks */
3217         __clear_bit(index, &hba->outstanding_tasks);
3218
3219         task_req_descp = hba->utmrdl_base_addr;
3220         ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3221
3222         if (ocs_value == OCS_SUCCESS) {
3223                 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3224                                 task_req_descp[index].task_rsp_upiu;
3225                 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
3226                 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
3227                 if (resp)
3228                         *resp = (u8)task_result;
3229         } else {
3230                 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3231                                 __func__, ocs_value);
3232         }
3233         spin_unlock_irqrestore(hba->host->host_lock, flags);
3234
3235         return ocs_value;
3236 }
3237
3238 /**
3239  * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3240  * @lrb: pointer to local reference block of completed command
3241  * @scsi_status: SCSI command status
3242  *
3243  * Returns value base on SCSI command status
3244  */
3245 static inline int
3246 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3247 {
3248         int result = 0;
3249
3250         switch (scsi_status) {
3251         case SAM_STAT_CHECK_CONDITION:
3252                 ufshcd_copy_sense_data(lrbp);
3253         case SAM_STAT_GOOD:
3254                 result |= DID_OK << 16 |
3255                           COMMAND_COMPLETE << 8 |
3256                           scsi_status;
3257                 break;
3258         case SAM_STAT_TASK_SET_FULL:
3259         case SAM_STAT_BUSY:
3260         case SAM_STAT_TASK_ABORTED:
3261                 ufshcd_copy_sense_data(lrbp);
3262                 result |= scsi_status;
3263                 break;
3264         default:
3265                 result |= DID_ERROR << 16;
3266                 break;
3267         } /* end of switch */
3268
3269         return result;
3270 }
3271
3272 /**
3273  * ufshcd_transfer_rsp_status - Get overall status of the response
3274  * @hba: per adapter instance
3275  * @lrb: pointer to local reference block of completed command
3276  *
3277  * Returns result of the command to notify SCSI midlayer
3278  */
3279 static inline int
3280 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3281 {
3282         int result = 0;
3283         int scsi_status;
3284         int ocs;
3285
3286         /* overall command status of utrd */
3287         ocs = ufshcd_get_tr_ocs(lrbp);
3288
3289         switch (ocs) {
3290         case OCS_SUCCESS:
3291                 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3292
3293                 switch (result) {
3294                 case UPIU_TRANSACTION_RESPONSE:
3295                         /*
3296                          * get the response UPIU result to extract
3297                          * the SCSI command status
3298                          */
3299                         result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3300
3301                         /*
3302                          * get the result based on SCSI status response
3303                          * to notify the SCSI midlayer of the command status
3304                          */
3305                         scsi_status = result & MASK_SCSI_STATUS;
3306                         result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3307
3308                         /*
3309                          * Currently we are only supporting BKOPs exception
3310                          * events hence we can ignore BKOPs exception event
3311                          * during power management callbacks. BKOPs exception
3312                          * event is not expected to be raised in runtime suspend
3313                          * callback as it allows the urgent bkops.
3314                          * During system suspend, we are anyway forcefully
3315                          * disabling the bkops and if urgent bkops is needed
3316                          * it will be enabled on system resume. Long term
3317                          * solution could be to abort the system suspend if
3318                          * UFS device needs urgent BKOPs.
3319                          */
3320                         if (!hba->pm_op_in_progress &&
3321                             ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3322                                 schedule_work(&hba->eeh_work);
3323                         break;
3324                 case UPIU_TRANSACTION_REJECT_UPIU:
3325                         /* TODO: handle Reject UPIU Response */
3326                         result = DID_ERROR << 16;
3327                         dev_err(hba->dev,
3328                                 "Reject UPIU not fully implemented\n");
3329                         break;
3330                 default:
3331                         result = DID_ERROR << 16;
3332                         dev_err(hba->dev,
3333                                 "Unexpected request response code = %x\n",
3334                                 result);
3335                         break;
3336                 }
3337                 break;
3338         case OCS_ABORTED:
3339                 result |= DID_ABORT << 16;
3340                 break;
3341         case OCS_INVALID_COMMAND_STATUS:
3342                 result |= DID_REQUEUE << 16;
3343                 break;
3344         case OCS_INVALID_CMD_TABLE_ATTR:
3345         case OCS_INVALID_PRDT_ATTR:
3346         case OCS_MISMATCH_DATA_BUF_SIZE:
3347         case OCS_MISMATCH_RESP_UPIU_SIZE:
3348         case OCS_PEER_COMM_FAILURE:
3349         case OCS_FATAL_ERROR:
3350         default:
3351                 result |= DID_ERROR << 16;
3352                 dev_err(hba->dev,
3353                 "OCS error from controller = %x\n", ocs);
3354                 break;
3355         } /* end of switch */
3356
3357         return result;
3358 }
3359
3360 /**
3361  * ufshcd_uic_cmd_compl - handle completion of uic command
3362  * @hba: per adapter instance
3363  * @intr_status: interrupt status generated by the controller
3364  */
3365 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3366 {
3367         if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3368                 hba->active_uic_cmd->argument2 |=
3369                         ufshcd_get_uic_cmd_result(hba);
3370                 hba->active_uic_cmd->argument3 =
3371                         ufshcd_get_dme_attr_val(hba);
3372                 complete(&hba->active_uic_cmd->done);
3373         }
3374
3375         if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3376                 complete(hba->uic_async_done);
3377 }
3378
3379 /**
3380  * ufshcd_transfer_req_compl - handle SCSI and query command completion
3381  * @hba: per adapter instance
3382  */
3383 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3384 {
3385         struct ufshcd_lrb *lrbp;
3386         struct scsi_cmnd *cmd;
3387         unsigned long completed_reqs;
3388         u32 tr_doorbell;
3389         int result;
3390         int index;
3391
3392         /* Resetting interrupt aggregation counters first and reading the
3393          * DOOR_BELL afterward allows us to handle all the completed requests.
3394          * In order to prevent other interrupts starvation the DB is read once
3395          * after reset. The down side of this solution is the possibility of
3396          * false interrupt if device completes another request after resetting
3397          * aggregation and before reading the DB.
3398          */
3399         if (ufshcd_is_intr_aggr_allowed(hba))
3400                 ufshcd_reset_intr_aggr(hba);
3401
3402         tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3403         completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3404
3405         for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3406                 lrbp = &hba->lrb[index];
3407                 cmd = lrbp->cmd;
3408                 if (cmd) {
3409                         result = ufshcd_transfer_rsp_status(hba, lrbp);
3410                         scsi_dma_unmap(cmd);
3411                         cmd->result = result;
3412                         /* Mark completed command as NULL in LRB */
3413                         lrbp->cmd = NULL;
3414                         clear_bit_unlock(index, &hba->lrb_in_use);
3415                         /* Do not touch lrbp after scsi done */
3416                         cmd->scsi_done(cmd);
3417                         __ufshcd_release(hba);
3418                 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3419                         if (hba->dev_cmd.complete)
3420                                 complete(hba->dev_cmd.complete);
3421                 }
3422         }
3423
3424         /* clear corresponding bits of completed commands */
3425         hba->outstanding_reqs ^= completed_reqs;
3426
3427         ufshcd_clk_scaling_update_busy(hba);
3428
3429         /* we might have free'd some tags above */
3430         wake_up(&hba->dev_cmd.tag_wq);
3431 }
3432
3433 /**
3434  * ufshcd_disable_ee - disable exception event
3435  * @hba: per-adapter instance
3436  * @mask: exception event to disable
3437  *
3438  * Disables exception event in the device so that the EVENT_ALERT
3439  * bit is not set.
3440  *
3441  * Returns zero on success, non-zero error value on failure.
3442  */
3443 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3444 {
3445         int err = 0;
3446         u32 val;
3447
3448         if (!(hba->ee_ctrl_mask & mask))
3449                 goto out;
3450
3451         val = hba->ee_ctrl_mask & ~mask;
3452         val &= 0xFFFF; /* 2 bytes */
3453         err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3454                         QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3455         if (!err)
3456                 hba->ee_ctrl_mask &= ~mask;
3457 out:
3458         return err;
3459 }
3460
3461 /**
3462  * ufshcd_enable_ee - enable exception event
3463  * @hba: per-adapter instance
3464  * @mask: exception event to enable
3465  *
3466  * Enable corresponding exception event in the device to allow
3467  * device to alert host in critical scenarios.
3468  *
3469  * Returns zero on success, non-zero error value on failure.
3470  */
3471 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3472 {
3473         int err = 0;
3474         u32 val;
3475
3476         if (hba->ee_ctrl_mask & mask)
3477                 goto out;
3478
3479         val = hba->ee_ctrl_mask | mask;
3480         val &= 0xFFFF; /* 2 bytes */
3481         err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3482                         QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3483         if (!err)
3484                 hba->ee_ctrl_mask |= mask;
3485 out:
3486         return err;
3487 }
3488
3489 /**
3490  * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3491  * @hba: per-adapter instance
3492  *
3493  * Allow device to manage background operations on its own. Enabling
3494  * this might lead to inconsistent latencies during normal data transfers
3495  * as the device is allowed to manage its own way of handling background
3496  * operations.
3497  *
3498  * Returns zero on success, non-zero on failure.
3499  */
3500 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3501 {
3502         int err = 0;
3503
3504         if (hba->auto_bkops_enabled)
3505                 goto out;
3506
3507         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3508                         QUERY_FLAG_IDN_BKOPS_EN, NULL);
3509         if (err) {
3510                 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3511                                 __func__, err);
3512                 goto out;
3513         }
3514
3515         hba->auto_bkops_enabled = true;
3516
3517         /* No need of URGENT_BKOPS exception from the device */
3518         err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3519         if (err)
3520                 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3521                                 __func__, err);
3522 out:
3523         return err;
3524 }
3525
3526 /**
3527  * ufshcd_disable_auto_bkops - block device in doing background operations
3528  * @hba: per-adapter instance
3529  *
3530  * Disabling background operations improves command response latency but
3531  * has drawback of device moving into critical state where the device is
3532  * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3533  * host is idle so that BKOPS are managed effectively without any negative
3534  * impacts.
3535  *
3536  * Returns zero on success, non-zero on failure.
3537  */
3538 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3539 {
3540         int err = 0;
3541
3542         if (!hba->auto_bkops_enabled)
3543                 goto out;
3544
3545         /*
3546          * If host assisted BKOPs is to be enabled, make sure
3547          * urgent bkops exception is allowed.
3548          */
3549         err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3550         if (err) {
3551                 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3552                                 __func__, err);
3553                 goto out;
3554         }
3555
3556         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3557                         QUERY_FLAG_IDN_BKOPS_EN, NULL);
3558         if (err) {
3559                 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3560                                 __func__, err);
3561                 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3562                 goto out;
3563         }
3564
3565         hba->auto_bkops_enabled = false;
3566 out:
3567         return err;
3568 }
3569
3570 /**
3571  * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3572  * @hba: per adapter instance
3573  *
3574  * After a device reset the device may toggle the BKOPS_EN flag
3575  * to default value. The s/w tracking variables should be updated
3576  * as well. Do this by forcing enable of auto bkops.
3577  */
3578 static void  ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3579 {
3580         hba->auto_bkops_enabled = false;
3581         hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3582         ufshcd_enable_auto_bkops(hba);
3583 }
3584
3585 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3586 {
3587         return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3588                         QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3589 }
3590
3591 /**
3592  * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3593  * @hba: per-adapter instance
3594  * @status: bkops_status value
3595  *
3596  * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3597  * flag in the device to permit background operations if the device
3598  * bkops_status is greater than or equal to "status" argument passed to
3599  * this function, disable otherwise.
3600  *
3601  * Returns 0 for success, non-zero in case of failure.
3602  *
3603  * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3604  * to know whether auto bkops is enabled or disabled after this function
3605  * returns control to it.
3606  */
3607 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3608                              enum bkops_status status)
3609 {
3610         int err;
3611         u32 curr_status = 0;
3612
3613         err = ufshcd_get_bkops_status(hba, &curr_status);
3614         if (err) {
3615                 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3616                                 __func__, err);
3617                 goto out;
3618         } else if (curr_status > BKOPS_STATUS_MAX) {
3619                 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3620                                 __func__, curr_status);
3621                 err = -EINVAL;
3622                 goto out;
3623         }
3624
3625         if (curr_status >= status)
3626                 err = ufshcd_enable_auto_bkops(hba);
3627         else
3628                 err = ufshcd_disable_auto_bkops(hba);
3629 out:
3630         return err;
3631 }
3632
3633 /**
3634  * ufshcd_urgent_bkops - handle urgent bkops exception event
3635  * @hba: per-adapter instance
3636  *
3637  * Enable fBackgroundOpsEn flag in the device to permit background
3638  * operations.
3639  *
3640  * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3641  * and negative error value for any other failure.
3642  */
3643 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3644 {
3645         return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3646 }
3647
3648 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3649 {
3650         return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3651                         QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3652 }
3653
3654 /**
3655  * ufshcd_exception_event_handler - handle exceptions raised by device
3656  * @work: pointer to work data
3657  *
3658  * Read bExceptionEventStatus attribute from the device and handle the
3659  * exception event accordingly.
3660  */
3661 static void ufshcd_exception_event_handler(struct work_struct *work)
3662 {
3663         struct ufs_hba *hba;
3664         int err;
3665         u32 status = 0;
3666         hba = container_of(work, struct ufs_hba, eeh_work);
3667
3668         pm_runtime_get_sync(hba->dev);
3669         err = ufshcd_get_ee_status(hba, &status);
3670         if (err) {
3671                 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3672                                 __func__, err);
3673                 goto out;
3674         }
3675
3676         status &= hba->ee_ctrl_mask;
3677         if (status & MASK_EE_URGENT_BKOPS) {
3678                 err = ufshcd_urgent_bkops(hba);
3679                 if (err < 0)
3680                         dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3681                                         __func__, err);
3682         }
3683 out:
3684         pm_runtime_put_sync(hba->dev);
3685         return;
3686 }
3687
3688 /**
3689  * ufshcd_err_handler - handle UFS errors that require s/w attention
3690  * @work: pointer to work structure
3691  */
3692 static void ufshcd_err_handler(struct work_struct *work)
3693 {
3694         struct ufs_hba *hba;
3695         unsigned long flags;
3696         u32 err_xfer = 0;
3697         u32 err_tm = 0;
3698         int err = 0;
3699         int tag;
3700
3701         hba = container_of(work, struct ufs_hba, eh_work);
3702
3703         pm_runtime_get_sync(hba->dev);
3704         ufshcd_hold(hba, false);
3705
3706         spin_lock_irqsave(hba->host->host_lock, flags);
3707         if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
3708                 spin_unlock_irqrestore(hba->host->host_lock, flags);
3709                 goto out;
3710         }
3711
3712         hba->ufshcd_state = UFSHCD_STATE_RESET;
3713         ufshcd_set_eh_in_progress(hba);
3714
3715         /* Complete requests that have door-bell cleared by h/w */
3716         ufshcd_transfer_req_compl(hba);
3717         ufshcd_tmc_handler(hba);
3718         spin_unlock_irqrestore(hba->host->host_lock, flags);
3719
3720         /* Clear pending transfer requests */
3721         for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs)
3722                 if (ufshcd_clear_cmd(hba, tag))
3723                         err_xfer |= 1 << tag;
3724
3725         /* Clear pending task management requests */
3726         for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs)
3727                 if (ufshcd_clear_tm_cmd(hba, tag))
3728                         err_tm |= 1 << tag;
3729
3730         /* Complete the requests that are cleared by s/w */
3731         spin_lock_irqsave(hba->host->host_lock, flags);
3732         ufshcd_transfer_req_compl(hba);
3733         ufshcd_tmc_handler(hba);
3734         spin_unlock_irqrestore(hba->host->host_lock, flags);
3735
3736         /* Fatal errors need reset */
3737         if (err_xfer || err_tm || (hba->saved_err & INT_FATAL_ERRORS) ||
3738                         ((hba->saved_err & UIC_ERROR) &&
3739                          (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR))) {
3740                 err = ufshcd_reset_and_restore(hba);
3741                 if (err) {
3742                         dev_err(hba->dev, "%s: reset and restore failed\n",
3743                                         __func__);
3744                         hba->ufshcd_state = UFSHCD_STATE_ERROR;
3745                 }
3746                 /*
3747                  * Inform scsi mid-layer that we did reset and allow to handle
3748                  * Unit Attention properly.
3749                  */
3750                 scsi_report_bus_reset(hba->host, 0);
3751                 hba->saved_err = 0;
3752                 hba->saved_uic_err = 0;
3753         }
3754         ufshcd_clear_eh_in_progress(hba);
3755
3756 out:
3757         scsi_unblock_requests(hba->host);
3758         ufshcd_release(hba);
3759         pm_runtime_put_sync(hba->dev);
3760 }
3761
3762 /**
3763  * ufshcd_update_uic_error - check and set fatal UIC error flags.
3764  * @hba: per-adapter instance
3765  */
3766 static void ufshcd_update_uic_error(struct ufs_hba *hba)
3767 {
3768         u32 reg;
3769
3770         /* PA_INIT_ERROR is fatal and needs UIC reset */
3771         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
3772         if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
3773                 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
3774
3775         /* UIC NL/TL/DME errors needs software retry */
3776         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
3777         if (reg)
3778                 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
3779
3780         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
3781         if (reg)
3782                 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
3783
3784         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
3785         if (reg)
3786                 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
3787
3788         dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
3789                         __func__, hba->uic_error);
3790 }
3791
3792 /**
3793  * ufshcd_check_errors - Check for errors that need s/w attention
3794  * @hba: per-adapter instance
3795  */
3796 static void ufshcd_check_errors(struct ufs_hba *hba)
3797 {
3798         bool queue_eh_work = false;
3799
3800         if (hba->errors & INT_FATAL_ERRORS)
3801                 queue_eh_work = true;
3802
3803         if (hba->errors & UIC_ERROR) {
3804                 hba->uic_error = 0;
3805                 ufshcd_update_uic_error(hba);
3806                 if (hba->uic_error)
3807                         queue_eh_work = true;
3808         }
3809
3810         if (queue_eh_work) {
3811                 /* handle fatal errors only when link is functional */
3812                 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
3813                         /* block commands from scsi mid-layer */
3814                         scsi_block_requests(hba->host);
3815
3816                         /* transfer error masks to sticky bits */
3817                         hba->saved_err |= hba->errors;
3818                         hba->saved_uic_err |= hba->uic_error;
3819
3820                         hba->ufshcd_state = UFSHCD_STATE_ERROR;
3821                         schedule_work(&hba->eh_work);
3822                 }
3823         }
3824         /*
3825          * if (!queue_eh_work) -
3826          * Other errors are either non-fatal where host recovers
3827          * itself without s/w intervention or errors that will be
3828          * handled by the SCSI core layer.
3829          */
3830 }
3831
3832 /**
3833  * ufshcd_tmc_handler - handle task management function completion
3834  * @hba: per adapter instance
3835  */
3836 static void ufshcd_tmc_handler(struct ufs_hba *hba)
3837 {
3838         u32 tm_doorbell;
3839
3840         tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
3841         hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
3842         wake_up(&hba->tm_wq);
3843 }
3844
3845 /**
3846  * ufshcd_sl_intr - Interrupt service routine
3847  * @hba: per adapter instance
3848  * @intr_status: contains interrupts generated by the controller
3849  */
3850 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
3851 {
3852         hba->errors = UFSHCD_ERROR_MASK & intr_status;
3853         if (hba->errors)
3854                 ufshcd_check_errors(hba);
3855
3856         if (intr_status & UFSHCD_UIC_MASK)
3857                 ufshcd_uic_cmd_compl(hba, intr_status);
3858
3859         if (intr_status & UTP_TASK_REQ_COMPL)
3860                 ufshcd_tmc_handler(hba);
3861
3862         if (intr_status & UTP_TRANSFER_REQ_COMPL)
3863                 ufshcd_transfer_req_compl(hba);
3864 }
3865
3866 /**
3867  * ufshcd_intr - Main interrupt service routine
3868  * @irq: irq number
3869  * @__hba: pointer to adapter instance
3870  *
3871  * Returns IRQ_HANDLED - If interrupt is valid
3872  *              IRQ_NONE - If invalid interrupt
3873  */
3874 static irqreturn_t ufshcd_intr(int irq, void *__hba)
3875 {
3876         u32 intr_status, enabled_intr_status;
3877         irqreturn_t retval = IRQ_NONE;
3878         struct ufs_hba *hba = __hba;
3879
3880         spin_lock(hba->host->host_lock);
3881         intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
3882         enabled_intr_status =
3883                 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
3884
3885         if (intr_status)
3886                 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
3887
3888         if (enabled_intr_status) {
3889                 ufshcd_sl_intr(hba, enabled_intr_status);
3890                 retval = IRQ_HANDLED;
3891         }
3892         spin_unlock(hba->host->host_lock);
3893         return retval;
3894 }
3895
3896 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
3897 {
3898         int err = 0;
3899         u32 mask = 1 << tag;
3900         unsigned long flags;
3901
3902         if (!test_bit(tag, &hba->outstanding_tasks))
3903                 goto out;
3904
3905         spin_lock_irqsave(hba->host->host_lock, flags);
3906         ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
3907         spin_unlock_irqrestore(hba->host->host_lock, flags);
3908
3909         /* poll for max. 1 sec to clear door bell register by h/w */
3910         err = ufshcd_wait_for_register(hba,
3911                         REG_UTP_TASK_REQ_DOOR_BELL,
3912                         mask, 0, 1000, 1000, true);
3913 out:
3914         return err;
3915 }
3916
3917 /**
3918  * ufshcd_issue_tm_cmd - issues task management commands to controller
3919  * @hba: per adapter instance
3920  * @lun_id: LUN ID to which TM command is sent
3921  * @task_id: task ID to which the TM command is applicable
3922  * @tm_function: task management function opcode
3923  * @tm_response: task management service response return value
3924  *
3925  * Returns non-zero value on error, zero on success.
3926  */
3927 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
3928                 u8 tm_function, u8 *tm_response)
3929 {
3930         struct utp_task_req_desc *task_req_descp;
3931         struct utp_upiu_task_req *task_req_upiup;
3932         struct Scsi_Host *host;
3933         unsigned long flags;
3934         int free_slot;
3935         int err;
3936         int task_tag;
3937
3938         host = hba->host;
3939
3940         /*
3941          * Get free slot, sleep if slots are unavailable.
3942          * Even though we use wait_event() which sleeps indefinitely,
3943          * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
3944          */
3945         wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
3946         ufshcd_hold(hba, false);
3947
3948         spin_lock_irqsave(host->host_lock, flags);
3949         task_req_descp = hba->utmrdl_base_addr;
3950         task_req_descp += free_slot;
3951
3952         /* Configure task request descriptor */
3953         task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
3954         task_req_descp->header.dword_2 =
3955                         cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
3956
3957         /* Configure task request UPIU */
3958         task_req_upiup =
3959                 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
3960         task_tag = hba->nutrs + free_slot;
3961         task_req_upiup->header.dword_0 =
3962                 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
3963                                               lun_id, task_tag);
3964         task_req_upiup->header.dword_1 =
3965                 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
3966         /*
3967          * The host shall provide the same value for LUN field in the basic
3968          * header and for Input Parameter.
3969          */
3970         task_req_upiup->input_param1 = cpu_to_be32(lun_id);
3971         task_req_upiup->input_param2 = cpu_to_be32(task_id);
3972
3973         /* send command to the controller */
3974         __set_bit(free_slot, &hba->outstanding_tasks);
3975
3976         /* Make sure descriptors are ready before ringing the task doorbell */
3977         wmb();
3978
3979         ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
3980
3981         spin_unlock_irqrestore(host->host_lock, flags);
3982
3983         /* wait until the task management command is completed */
3984         err = wait_event_timeout(hba->tm_wq,
3985                         test_bit(free_slot, &hba->tm_condition),
3986                         msecs_to_jiffies(TM_CMD_TIMEOUT));
3987         if (!err) {
3988                 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
3989                                 __func__, tm_function);
3990                 if (ufshcd_clear_tm_cmd(hba, free_slot))
3991                         dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
3992                                         __func__, free_slot);
3993                 err = -ETIMEDOUT;
3994         } else {
3995                 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
3996         }
3997
3998         clear_bit(free_slot, &hba->tm_condition);
3999         ufshcd_put_tm_slot(hba, free_slot);
4000         wake_up(&hba->tm_tag_wq);
4001
4002         ufshcd_release(hba);
4003         return err;
4004 }
4005
4006 /**
4007  * ufshcd_eh_device_reset_handler - device reset handler registered to
4008  *                                    scsi layer.
4009  * @cmd: SCSI command pointer
4010  *
4011  * Returns SUCCESS/FAILED
4012  */
4013 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
4014 {
4015         struct Scsi_Host *host;
4016         struct ufs_hba *hba;
4017         unsigned int tag;
4018         u32 pos;
4019         int err;
4020         u8 resp = 0xF;
4021         struct ufshcd_lrb *lrbp;
4022         unsigned long flags;
4023
4024         host = cmd->device->host;
4025         hba = shost_priv(host);
4026         tag = cmd->request->tag;
4027
4028         lrbp = &hba->lrb[tag];
4029         err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4030         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4031                 if (!err)
4032                         err = resp;
4033                 goto out;
4034         }
4035
4036         /* clear the commands that were pending for corresponding LUN */
4037         for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4038                 if (hba->lrb[pos].lun == lrbp->lun) {
4039                         err = ufshcd_clear_cmd(hba, pos);
4040                         if (err)
4041                                 break;
4042                 }
4043         }
4044         spin_lock_irqsave(host->host_lock, flags);
4045         ufshcd_transfer_req_compl(hba);
4046         spin_unlock_irqrestore(host->host_lock, flags);
4047 out:
4048         if (!err) {
4049                 err = SUCCESS;
4050         } else {
4051                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4052                 err = FAILED;
4053         }
4054         return err;
4055 }
4056
4057 /**
4058  * ufshcd_abort - abort a specific command
4059  * @cmd: SCSI command pointer
4060  *
4061  * Abort the pending command in device by sending UFS_ABORT_TASK task management
4062  * command, and in host controller by clearing the door-bell register. There can
4063  * be race between controller sending the command to the device while abort is
4064  * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4065  * really issued and then try to abort it.
4066  *
4067  * Returns SUCCESS/FAILED
4068  */
4069 static int ufshcd_abort(struct scsi_cmnd *cmd)
4070 {
4071         struct Scsi_Host *host;
4072         struct ufs_hba *hba;
4073         unsigned long flags;
4074         unsigned int tag;
4075         int err = 0;
4076         int poll_cnt;
4077         u8 resp = 0xF;
4078         struct ufshcd_lrb *lrbp;
4079         u32 reg;
4080
4081         host = cmd->device->host;
4082         hba = shost_priv(host);
4083         tag = cmd->request->tag;
4084         if (!ufshcd_valid_tag(hba, tag)) {
4085                 dev_err(hba->dev,
4086                         "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4087                         __func__, tag, cmd, cmd->request);
4088                 BUG();
4089         }
4090
4091         ufshcd_hold(hba, false);
4092         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4093         /* If command is already aborted/completed, return SUCCESS */
4094         if (!(test_bit(tag, &hba->outstanding_reqs))) {
4095                 dev_err(hba->dev,
4096                         "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4097                         __func__, tag, hba->outstanding_reqs, reg);
4098                 goto out;
4099         }
4100
4101         if (!(reg & (1 << tag))) {
4102                 dev_err(hba->dev,
4103                 "%s: cmd was completed, but without a notifying intr, tag = %d",
4104                 __func__, tag);
4105         }
4106
4107         lrbp = &hba->lrb[tag];
4108         for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4109                 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4110                                 UFS_QUERY_TASK, &resp);
4111                 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4112                         /* cmd pending in the device */
4113                         break;
4114                 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4115                         /*
4116                          * cmd not pending in the device, check if it is
4117                          * in transition.
4118                          */
4119                         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4120                         if (reg & (1 << tag)) {
4121                                 /* sleep for max. 200us to stabilize */
4122                                 usleep_range(100, 200);
4123                                 continue;
4124                         }
4125                         /* command completed already */
4126                         goto out;
4127                 } else {
4128                         if (!err)
4129                                 err = resp; /* service response error */
4130                         goto out;
4131                 }
4132         }
4133
4134         if (!poll_cnt) {
4135                 err = -EBUSY;
4136                 goto out;
4137         }
4138
4139         err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4140                         UFS_ABORT_TASK, &resp);
4141         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4142                 if (!err)
4143                         err = resp; /* service response error */
4144                 goto out;
4145         }
4146
4147         err = ufshcd_clear_cmd(hba, tag);
4148         if (err)
4149                 goto out;
4150
4151         scsi_dma_unmap(cmd);
4152
4153         spin_lock_irqsave(host->host_lock, flags);
4154         ufshcd_outstanding_req_clear(hba, tag);
4155         hba->lrb[tag].cmd = NULL;
4156         spin_unlock_irqrestore(host->host_lock, flags);
4157
4158         clear_bit_unlock(tag, &hba->lrb_in_use);
4159         wake_up(&hba->dev_cmd.tag_wq);
4160
4161 out:
4162         if (!err) {
4163                 err = SUCCESS;
4164         } else {
4165                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4166                 err = FAILED;
4167         }
4168
4169         /*
4170          * This ufshcd_release() corresponds to the original scsi cmd that got
4171          * aborted here (as we won't get any IRQ for it).
4172          */
4173         ufshcd_release(hba);
4174         return err;
4175 }
4176
4177 /**
4178  * ufshcd_host_reset_and_restore - reset and restore host controller
4179  * @hba: per-adapter instance
4180  *
4181  * Note that host controller reset may issue DME_RESET to
4182  * local and remote (device) Uni-Pro stack and the attributes
4183  * are reset to default state.
4184  *
4185  * Returns zero on success, non-zero on failure
4186  */
4187 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4188 {
4189         int err;
4190         unsigned long flags;
4191
4192         /* Reset the host controller */
4193         spin_lock_irqsave(hba->host->host_lock, flags);
4194         ufshcd_hba_stop(hba, false);
4195         spin_unlock_irqrestore(hba->host->host_lock, flags);
4196
4197         err = ufshcd_hba_enable(hba);
4198         if (err)
4199                 goto out;
4200
4201         /* Establish the link again and restore the device */
4202         err = ufshcd_probe_hba(hba);
4203
4204         if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
4205                 err = -EIO;
4206 out:
4207         if (err)
4208                 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4209
4210         return err;
4211 }
4212
4213 /**
4214  * ufshcd_reset_and_restore - reset and re-initialize host/device
4215  * @hba: per-adapter instance
4216  *
4217  * Reset and recover device, host and re-establish link. This
4218  * is helpful to recover the communication in fatal error conditions.
4219  *
4220  * Returns zero on success, non-zero on failure
4221  */
4222 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4223 {
4224         int err = 0;
4225         unsigned long flags;
4226         int retries = MAX_HOST_RESET_RETRIES;
4227
4228         do {
4229                 err = ufshcd_host_reset_and_restore(hba);
4230         } while (err && --retries);
4231
4232         /*
4233          * After reset the door-bell might be cleared, complete
4234          * outstanding requests in s/w here.
4235          */
4236         spin_lock_irqsave(hba->host->host_lock, flags);
4237         ufshcd_transfer_req_compl(hba);
4238         ufshcd_tmc_handler(hba);
4239         spin_unlock_irqrestore(hba->host->host_lock, flags);
4240
4241         return err;
4242 }
4243
4244 /**
4245  * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4246  * @cmd - SCSI command pointer
4247  *
4248  * Returns SUCCESS/FAILED
4249  */
4250 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4251 {
4252         int err;
4253         unsigned long flags;
4254         struct ufs_hba *hba;
4255
4256         hba = shost_priv(cmd->device->host);
4257
4258         ufshcd_hold(hba, false);
4259         /*
4260          * Check if there is any race with fatal error handling.
4261          * If so, wait for it to complete. Even though fatal error
4262          * handling does reset and restore in some cases, don't assume
4263          * anything out of it. We are just avoiding race here.
4264          */
4265         do {
4266                 spin_lock_irqsave(hba->host->host_lock, flags);
4267                 if (!(work_pending(&hba->eh_work) ||
4268                                 hba->ufshcd_state == UFSHCD_STATE_RESET))
4269                         break;
4270                 spin_unlock_irqrestore(hba->host->host_lock, flags);
4271                 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4272                 flush_work(&hba->eh_work);
4273         } while (1);
4274
4275         hba->ufshcd_state = UFSHCD_STATE_RESET;
4276         ufshcd_set_eh_in_progress(hba);
4277         spin_unlock_irqrestore(hba->host->host_lock, flags);
4278
4279         err = ufshcd_reset_and_restore(hba);
4280
4281         spin_lock_irqsave(hba->host->host_lock, flags);
4282         if (!err) {
4283                 err = SUCCESS;
4284                 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4285         } else {
4286                 err = FAILED;
4287                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4288         }
4289         ufshcd_clear_eh_in_progress(hba);
4290         spin_unlock_irqrestore(hba->host->host_lock, flags);
4291
4292         ufshcd_release(hba);
4293         return err;
4294 }
4295
4296 /**
4297  * ufshcd_get_max_icc_level - calculate the ICC level
4298  * @sup_curr_uA: max. current supported by the regulator
4299  * @start_scan: row at the desc table to start scan from
4300  * @buff: power descriptor buffer
4301  *
4302  * Returns calculated max ICC level for specific regulator
4303  */
4304 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4305 {
4306         int i;
4307         int curr_uA;
4308         u16 data;
4309         u16 unit;
4310
4311         for (i = start_scan; i >= 0; i--) {
4312                 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4313                 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4314                                                 ATTR_ICC_LVL_UNIT_OFFSET;
4315                 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4316                 switch (unit) {
4317                 case UFSHCD_NANO_AMP:
4318                         curr_uA = curr_uA / 1000;
4319                         break;
4320                 case UFSHCD_MILI_AMP:
4321                         curr_uA = curr_uA * 1000;
4322                         break;
4323                 case UFSHCD_AMP:
4324                         curr_uA = curr_uA * 1000 * 1000;
4325                         break;
4326                 case UFSHCD_MICRO_AMP:
4327                 default:
4328                         break;
4329                 }
4330                 if (sup_curr_uA >= curr_uA)
4331                         break;
4332         }
4333         if (i < 0) {
4334                 i = 0;
4335                 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4336         }
4337
4338         return (u32)i;
4339 }
4340
4341 /**
4342  * ufshcd_calc_icc_level - calculate the max ICC level
4343  * In case regulators are not initialized we'll return 0
4344  * @hba: per-adapter instance
4345  * @desc_buf: power descriptor buffer to extract ICC levels from.
4346  * @len: length of desc_buff
4347  *
4348  * Returns calculated ICC level
4349  */
4350 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4351                                                         u8 *desc_buf, int len)
4352 {
4353         u32 icc_level = 0;
4354
4355         if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4356                                                 !hba->vreg_info.vccq2) {
4357                 dev_err(hba->dev,
4358                         "%s: Regulator capability was not set, actvIccLevel=%d",
4359                                                         __func__, icc_level);
4360                 goto out;
4361         }
4362
4363         if (hba->vreg_info.vcc)
4364                 icc_level = ufshcd_get_max_icc_level(
4365                                 hba->vreg_info.vcc->max_uA,
4366                                 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4367                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4368
4369         if (hba->vreg_info.vccq)
4370                 icc_level = ufshcd_get_max_icc_level(
4371                                 hba->vreg_info.vccq->max_uA,
4372                                 icc_level,
4373                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4374
4375         if (hba->vreg_info.vccq2)
4376                 icc_level = ufshcd_get_max_icc_level(
4377                                 hba->vreg_info.vccq2->max_uA,
4378                                 icc_level,
4379                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4380 out:
4381         return icc_level;
4382 }
4383
4384 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4385 {
4386         int ret;
4387         int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4388         u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4389
4390         ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4391         if (ret) {
4392                 dev_err(hba->dev,
4393                         "%s: Failed reading power descriptor.len = %d ret = %d",
4394                         __func__, buff_len, ret);
4395                 return;
4396         }
4397
4398         hba->init_prefetch_data.icc_level =
4399                         ufshcd_find_max_sup_active_icc_level(hba,
4400                         desc_buf, buff_len);
4401         dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4402                         __func__, hba->init_prefetch_data.icc_level);
4403
4404         ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4405                 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4406                 &hba->init_prefetch_data.icc_level);
4407
4408         if (ret)
4409                 dev_err(hba->dev,
4410                         "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4411                         __func__, hba->init_prefetch_data.icc_level , ret);
4412
4413 }
4414
4415 /**
4416  * ufshcd_scsi_add_wlus - Adds required W-LUs
4417  * @hba: per-adapter instance
4418  *
4419  * UFS device specification requires the UFS devices to support 4 well known
4420  * logical units:
4421  *      "REPORT_LUNS" (address: 01h)
4422  *      "UFS Device" (address: 50h)
4423  *      "RPMB" (address: 44h)
4424  *      "BOOT" (address: 30h)
4425  * UFS device's power management needs to be controlled by "POWER CONDITION"
4426  * field of SSU (START STOP UNIT) command. But this "power condition" field
4427  * will take effect only when its sent to "UFS device" well known logical unit
4428  * hence we require the scsi_device instance to represent this logical unit in
4429  * order for the UFS host driver to send the SSU command for power management.
4430
4431  * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4432  * Block) LU so user space process can control this LU. User space may also
4433  * want to have access to BOOT LU.
4434
4435  * This function adds scsi device instances for each of all well known LUs
4436  * (except "REPORT LUNS" LU).
4437  *
4438  * Returns zero on success (all required W-LUs are added successfully),
4439  * non-zero error value on failure (if failed to add any of the required W-LU).
4440  */
4441 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4442 {
4443         int ret = 0;
4444         struct scsi_device *sdev_rpmb;
4445         struct scsi_device *sdev_boot;
4446
4447         hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4448                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4449         if (IS_ERR(hba->sdev_ufs_device)) {
4450                 ret = PTR_ERR(hba->sdev_ufs_device);
4451                 hba->sdev_ufs_device = NULL;
4452                 goto out;
4453         }
4454         scsi_device_put(hba->sdev_ufs_device);
4455
4456         sdev_boot = __scsi_add_device(hba->host, 0, 0,
4457                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4458         if (IS_ERR(sdev_boot)) {
4459                 ret = PTR_ERR(sdev_boot);
4460                 goto remove_sdev_ufs_device;
4461         }
4462         scsi_device_put(sdev_boot);
4463
4464         sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4465                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4466         if (IS_ERR(sdev_rpmb)) {
4467                 ret = PTR_ERR(sdev_rpmb);
4468                 goto remove_sdev_boot;
4469         }
4470         scsi_device_put(sdev_rpmb);
4471         goto out;
4472
4473 remove_sdev_boot:
4474         scsi_remove_device(sdev_boot);
4475 remove_sdev_ufs_device:
4476         scsi_remove_device(hba->sdev_ufs_device);
4477 out:
4478         return ret;
4479 }
4480
4481 /**
4482  * ufshcd_probe_hba - probe hba to detect device and initialize
4483  * @hba: per-adapter instance
4484  *
4485  * Execute link-startup and verify device initialization
4486  */
4487 static int ufshcd_probe_hba(struct ufs_hba *hba)
4488 {
4489         int ret;
4490
4491         ret = ufshcd_link_startup(hba);
4492         if (ret)
4493                 goto out;
4494
4495         ufshcd_init_pwr_info(hba);
4496
4497         /* UniPro link is active now */
4498         ufshcd_set_link_active(hba);
4499
4500         ret = ufshcd_verify_dev_init(hba);
4501         if (ret)
4502                 goto out;
4503
4504         ret = ufshcd_complete_dev_init(hba);
4505         if (ret)
4506                 goto out;
4507
4508         /* UFS device is also active now */
4509         ufshcd_set_ufs_dev_active(hba);
4510         ufshcd_force_reset_auto_bkops(hba);
4511         hba->wlun_dev_clr_ua = true;
4512
4513         if (ufshcd_get_max_pwr_mode(hba)) {
4514                 dev_err(hba->dev,
4515                         "%s: Failed getting max supported power mode\n",
4516                         __func__);
4517         } else {
4518                 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4519                 if (ret)
4520                         dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4521                                         __func__, ret);
4522         }
4523
4524         /* set the state as operational after switching to desired gear */
4525         hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4526         /*
4527          * If we are in error handling context or in power management callbacks
4528          * context, no need to scan the host
4529          */
4530         if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4531                 bool flag;
4532
4533                 /* clear any previous UFS device information */
4534                 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
4535                 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4536                                 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
4537                         hba->dev_info.f_power_on_wp_en = flag;
4538
4539                 if (!hba->is_init_prefetch)
4540                         ufshcd_init_icc_levels(hba);
4541
4542                 /* Add required well known logical units to scsi mid layer */
4543                 if (ufshcd_scsi_add_wlus(hba))
4544                         goto out;
4545
4546                 scsi_scan_host(hba->host);
4547                 pm_runtime_put_sync(hba->dev);
4548         }
4549
4550         if (!hba->is_init_prefetch)
4551                 hba->is_init_prefetch = true;
4552
4553         /* Resume devfreq after UFS device is detected */
4554         if (ufshcd_is_clkscaling_enabled(hba))
4555                 devfreq_resume_device(hba->devfreq);
4556
4557 out:
4558         /*
4559          * If we failed to initialize the device or the device is not
4560          * present, turn off the power/clocks etc.
4561          */
4562         if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4563                 pm_runtime_put_sync(hba->dev);
4564                 ufshcd_hba_exit(hba);
4565         }
4566
4567         return ret;
4568 }
4569
4570 /**
4571  * ufshcd_async_scan - asynchronous execution for probing hba
4572  * @data: data pointer to pass to this function
4573  * @cookie: cookie data
4574  */
4575 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4576 {
4577         struct ufs_hba *hba = (struct ufs_hba *)data;
4578
4579         ufshcd_probe_hba(hba);
4580 }
4581
4582 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
4583 {
4584         unsigned long flags;
4585         struct Scsi_Host *host;
4586         struct ufs_hba *hba;
4587         int index;
4588         bool found = false;
4589
4590         if (!scmd || !scmd->device || !scmd->device->host)
4591                 return BLK_EH_NOT_HANDLED;
4592
4593         host = scmd->device->host;
4594         hba = shost_priv(host);
4595         if (!hba)
4596                 return BLK_EH_NOT_HANDLED;
4597
4598         spin_lock_irqsave(host->host_lock, flags);
4599
4600         for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
4601                 if (hba->lrb[index].cmd == scmd) {
4602                         found = true;
4603                         break;
4604                 }
4605         }
4606
4607         spin_unlock_irqrestore(host->host_lock, flags);
4608
4609         /*
4610          * Bypass SCSI error handling and reset the block layer timer if this
4611          * SCSI command was not actually dispatched to UFS driver, otherwise
4612          * let SCSI layer handle the error as usual.
4613          */
4614         return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
4615 }
4616
4617 static struct scsi_host_template ufshcd_driver_template = {
4618         .module                 = THIS_MODULE,
4619         .name                   = UFSHCD,
4620         .proc_name              = UFSHCD,
4621         .queuecommand           = ufshcd_queuecommand,
4622         .slave_alloc            = ufshcd_slave_alloc,
4623         .slave_configure        = ufshcd_slave_configure,
4624         .slave_destroy          = ufshcd_slave_destroy,
4625         .change_queue_depth     = ufshcd_change_queue_depth,
4626         .eh_abort_handler       = ufshcd_abort,
4627         .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4628         .eh_host_reset_handler   = ufshcd_eh_host_reset_handler,
4629         .eh_timed_out           = ufshcd_eh_timed_out,
4630         .this_id                = -1,
4631         .sg_tablesize           = SG_ALL,
4632         .cmd_per_lun            = UFSHCD_CMD_PER_LUN,
4633         .can_queue              = UFSHCD_CAN_QUEUE,
4634         .max_host_blocked       = 1,
4635         .track_queue_depth      = 1,
4636 };
4637
4638 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4639                                    int ua)
4640 {
4641         int ret;
4642
4643         if (!vreg)
4644                 return 0;
4645
4646         ret = regulator_set_load(vreg->reg, ua);
4647         if (ret < 0) {
4648                 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4649                                 __func__, vreg->name, ua, ret);
4650         }
4651
4652         return ret;
4653 }
4654
4655 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
4656                                          struct ufs_vreg *vreg)
4657 {
4658         return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
4659 }
4660
4661 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
4662                                          struct ufs_vreg *vreg)
4663 {
4664         return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
4665 }
4666
4667 static int ufshcd_config_vreg(struct device *dev,
4668                 struct ufs_vreg *vreg, bool on)
4669 {
4670         int ret = 0;
4671         struct regulator *reg = vreg->reg;
4672         const char *name = vreg->name;
4673         int min_uV, uA_load;
4674
4675         BUG_ON(!vreg);
4676
4677         if (regulator_count_voltages(reg) > 0) {
4678                 min_uV = on ? vreg->min_uV : 0;
4679                 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
4680                 if (ret) {
4681                         dev_err(dev, "%s: %s set voltage failed, err=%d\n",
4682                                         __func__, name, ret);
4683                         goto out;
4684                 }
4685
4686                 uA_load = on ? vreg->max_uA : 0;
4687                 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
4688                 if (ret)
4689                         goto out;
4690         }
4691 out:
4692         return ret;
4693 }
4694
4695 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
4696 {
4697         int ret = 0;
4698
4699         if (!vreg || vreg->enabled)
4700                 goto out;
4701
4702         ret = ufshcd_config_vreg(dev, vreg, true);
4703         if (!ret)
4704                 ret = regulator_enable(vreg->reg);
4705
4706         if (!ret)
4707                 vreg->enabled = true;
4708         else
4709                 dev_err(dev, "%s: %s enable failed, err=%d\n",
4710                                 __func__, vreg->name, ret);
4711 out:
4712         return ret;
4713 }
4714
4715 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
4716 {
4717         int ret = 0;
4718
4719         if (!vreg || !vreg->enabled)
4720                 goto out;
4721
4722         ret = regulator_disable(vreg->reg);
4723
4724         if (!ret) {
4725                 /* ignore errors on applying disable config */
4726                 ufshcd_config_vreg(dev, vreg, false);
4727                 vreg->enabled = false;
4728         } else {
4729                 dev_err(dev, "%s: %s disable failed, err=%d\n",
4730                                 __func__, vreg->name, ret);
4731         }
4732 out:
4733         return ret;
4734 }
4735
4736 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
4737 {
4738         int ret = 0;
4739         struct device *dev = hba->dev;
4740         struct ufs_vreg_info *info = &hba->vreg_info;
4741
4742         if (!info)
4743                 goto out;
4744
4745         ret = ufshcd_toggle_vreg(dev, info->vcc, on);
4746         if (ret)
4747                 goto out;
4748
4749         ret = ufshcd_toggle_vreg(dev, info->vccq, on);
4750         if (ret)
4751                 goto out;
4752
4753         ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
4754         if (ret)
4755                 goto out;
4756
4757 out:
4758         if (ret) {
4759                 ufshcd_toggle_vreg(dev, info->vccq2, false);
4760                 ufshcd_toggle_vreg(dev, info->vccq, false);
4761                 ufshcd_toggle_vreg(dev, info->vcc, false);
4762         }
4763         return ret;
4764 }
4765
4766 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
4767 {
4768         struct ufs_vreg_info *info = &hba->vreg_info;
4769
4770         if (info)
4771                 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
4772
4773         return 0;
4774 }
4775
4776 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
4777 {
4778         int ret = 0;
4779
4780         if (!vreg)
4781                 goto out;
4782
4783         vreg->reg = devm_regulator_get(dev, vreg->name);
4784         if (IS_ERR(vreg->reg)) {
4785                 ret = PTR_ERR(vreg->reg);
4786                 dev_err(dev, "%s: %s get failed, err=%d\n",
4787                                 __func__, vreg->name, ret);
4788         }
4789 out:
4790         return ret;
4791 }
4792
4793 static int ufshcd_init_vreg(struct ufs_hba *hba)
4794 {
4795         int ret = 0;
4796         struct device *dev = hba->dev;
4797         struct ufs_vreg_info *info = &hba->vreg_info;
4798
4799         if (!info)
4800                 goto out;
4801
4802         ret = ufshcd_get_vreg(dev, info->vcc);
4803         if (ret)
4804                 goto out;
4805
4806         ret = ufshcd_get_vreg(dev, info->vccq);
4807         if (ret)
4808                 goto out;
4809
4810         ret = ufshcd_get_vreg(dev, info->vccq2);
4811 out:
4812         return ret;
4813 }
4814
4815 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
4816 {
4817         struct ufs_vreg_info *info = &hba->vreg_info;
4818
4819         if (info)
4820                 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
4821
4822         return 0;
4823 }
4824
4825 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
4826                                         bool skip_ref_clk)
4827 {
4828         int ret = 0;
4829         struct ufs_clk_info *clki;
4830         struct list_head *head = &hba->clk_list_head;
4831         unsigned long flags;
4832
4833         if (!head || list_empty(head))
4834                 goto out;
4835
4836         list_for_each_entry(clki, head, list) {
4837                 if (!IS_ERR_OR_NULL(clki->clk)) {
4838                         if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
4839                                 continue;
4840
4841                         if (on && !clki->enabled) {
4842                                 ret = clk_prepare_enable(clki->clk);
4843                                 if (ret) {
4844                                         dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
4845                                                 __func__, clki->name, ret);
4846                                         goto out;
4847                                 }
4848                         } else if (!on && clki->enabled) {
4849                                 clk_disable_unprepare(clki->clk);
4850                         }
4851                         clki->enabled = on;
4852                         dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
4853                                         clki->name, on ? "en" : "dis");
4854                 }
4855         }
4856
4857         ret = ufshcd_vops_setup_clocks(hba, on);
4858 out:
4859         if (ret) {
4860                 list_for_each_entry(clki, head, list) {
4861                         if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
4862                                 clk_disable_unprepare(clki->clk);
4863                 }
4864         } else if (on) {
4865                 spin_lock_irqsave(hba->host->host_lock, flags);
4866                 hba->clk_gating.state = CLKS_ON;
4867                 spin_unlock_irqrestore(hba->host->host_lock, flags);
4868         }
4869         return ret;
4870 }
4871
4872 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
4873 {
4874         return  __ufshcd_setup_clocks(hba, on, false);
4875 }
4876
4877 static int ufshcd_init_clocks(struct ufs_hba *hba)
4878 {
4879         int ret = 0;
4880         struct ufs_clk_info *clki;
4881         struct device *dev = hba->dev;
4882         struct list_head *head = &hba->clk_list_head;
4883
4884         if (!head || list_empty(head))
4885                 goto out;
4886
4887         list_for_each_entry(clki, head, list) {
4888                 if (!clki->name)
4889                         continue;
4890
4891                 clki->clk = devm_clk_get(dev, clki->name);
4892                 if (IS_ERR(clki->clk)) {
4893                         ret = PTR_ERR(clki->clk);
4894                         dev_err(dev, "%s: %s clk get failed, %d\n",
4895                                         __func__, clki->name, ret);
4896                         goto out;
4897                 }
4898
4899                 if (clki->max_freq) {
4900                         ret = clk_set_rate(clki->clk, clki->max_freq);
4901                         if (ret) {
4902                                 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
4903                                         __func__, clki->name,
4904                                         clki->max_freq, ret);
4905                                 goto out;
4906                         }
4907                         clki->curr_freq = clki->max_freq;
4908                 }
4909                 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
4910                                 clki->name, clk_get_rate(clki->clk));
4911         }
4912 out:
4913         return ret;
4914 }
4915
4916 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
4917 {
4918         int err = 0;
4919
4920         if (!hba->vops)
4921                 goto out;
4922
4923         err = ufshcd_vops_init(hba);
4924         if (err)
4925                 goto out;
4926
4927         err = ufshcd_vops_setup_regulators(hba, true);
4928         if (err)
4929                 goto out_exit;
4930
4931         goto out;
4932
4933 out_exit:
4934         ufshcd_vops_exit(hba);
4935 out:
4936         if (err)
4937                 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
4938                         __func__, ufshcd_get_var_name(hba), err);
4939         return err;
4940 }
4941
4942 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
4943 {
4944         if (!hba->vops)
4945                 return;
4946
4947         ufshcd_vops_setup_clocks(hba, false);
4948
4949         ufshcd_vops_setup_regulators(hba, false);
4950
4951         ufshcd_vops_exit(hba);
4952 }
4953
4954 static int ufshcd_hba_init(struct ufs_hba *hba)
4955 {
4956         int err;
4957
4958         /*
4959          * Handle host controller power separately from the UFS device power
4960          * rails as it will help controlling the UFS host controller power
4961          * collapse easily which is different than UFS device power collapse.
4962          * Also, enable the host controller power before we go ahead with rest
4963          * of the initialization here.
4964          */
4965         err = ufshcd_init_hba_vreg(hba);
4966         if (err)
4967                 goto out;
4968
4969         err = ufshcd_setup_hba_vreg(hba, true);
4970         if (err)
4971                 goto out;
4972
4973         err = ufshcd_init_clocks(hba);
4974         if (err)
4975                 goto out_disable_hba_vreg;
4976
4977         err = ufshcd_setup_clocks(hba, true);
4978         if (err)
4979                 goto out_disable_hba_vreg;
4980
4981         err = ufshcd_init_vreg(hba);
4982         if (err)
4983                 goto out_disable_clks;
4984
4985         err = ufshcd_setup_vreg(hba, true);
4986         if (err)
4987                 goto out_disable_clks;
4988
4989         err = ufshcd_variant_hba_init(hba);
4990         if (err)
4991                 goto out_disable_vreg;
4992
4993         hba->is_powered = true;
4994         goto out;
4995
4996 out_disable_vreg:
4997         ufshcd_setup_vreg(hba, false);
4998 out_disable_clks:
4999         ufshcd_setup_clocks(hba, false);
5000 out_disable_hba_vreg:
5001         ufshcd_setup_hba_vreg(hba, false);
5002 out:
5003         return err;
5004 }
5005
5006 static void ufshcd_hba_exit(struct ufs_hba *hba)
5007 {
5008         if (hba->is_powered) {
5009                 ufshcd_variant_hba_exit(hba);
5010                 ufshcd_setup_vreg(hba, false);
5011                 ufshcd_setup_clocks(hba, false);
5012                 ufshcd_setup_hba_vreg(hba, false);
5013                 hba->is_powered = false;
5014         }
5015 }
5016
5017 static int
5018 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5019 {
5020         unsigned char cmd[6] = {REQUEST_SENSE,
5021                                 0,
5022                                 0,
5023                                 0,
5024                                 SCSI_SENSE_BUFFERSIZE,
5025                                 0};
5026         char *buffer;
5027         int ret;
5028
5029         buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5030         if (!buffer) {
5031                 ret = -ENOMEM;
5032                 goto out;
5033         }
5034
5035         ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5036                                 SCSI_SENSE_BUFFERSIZE, NULL,
5037                                 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5038         if (ret)
5039                 pr_err("%s: failed with err %d\n", __func__, ret);
5040
5041         kfree(buffer);
5042 out:
5043         return ret;
5044 }
5045
5046 /**
5047  * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5048  *                           power mode
5049  * @hba: per adapter instance
5050  * @pwr_mode: device power mode to set
5051  *
5052  * Returns 0 if requested power mode is set successfully
5053  * Returns non-zero if failed to set the requested power mode
5054  */
5055 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5056                                      enum ufs_dev_pwr_mode pwr_mode)
5057 {
5058         unsigned char cmd[6] = { START_STOP };
5059         struct scsi_sense_hdr sshdr;
5060         struct scsi_device *sdp;
5061         unsigned long flags;
5062         int ret;
5063
5064         spin_lock_irqsave(hba->host->host_lock, flags);
5065         sdp = hba->sdev_ufs_device;
5066         if (sdp) {
5067                 ret = scsi_device_get(sdp);
5068                 if (!ret && !scsi_device_online(sdp)) {
5069                         ret = -ENODEV;
5070                         scsi_device_put(sdp);
5071                 }
5072         } else {
5073                 ret = -ENODEV;
5074         }
5075         spin_unlock_irqrestore(hba->host->host_lock, flags);
5076
5077         if (ret)
5078                 return ret;
5079
5080         /*
5081          * If scsi commands fail, the scsi mid-layer schedules scsi error-
5082          * handling, which would wait for host to be resumed. Since we know
5083          * we are functional while we are here, skip host resume in error
5084          * handling context.
5085          */
5086         hba->host->eh_noresume = 1;
5087         if (hba->wlun_dev_clr_ua) {
5088                 ret = ufshcd_send_request_sense(hba, sdp);
5089                 if (ret)
5090                         goto out;
5091                 /* Unit attention condition is cleared now */
5092                 hba->wlun_dev_clr_ua = false;
5093         }
5094
5095         cmd[4] = pwr_mode << 4;
5096
5097         /*
5098          * Current function would be generally called from the power management
5099          * callbacks hence set the REQ_PM flag so that it doesn't resume the
5100          * already suspended childs.
5101          */
5102         ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5103                                      START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5104         if (ret) {
5105                 sdev_printk(KERN_WARNING, sdp,
5106                             "START_STOP failed for power mode: %d, result %x\n",
5107                             pwr_mode, ret);
5108                 if (driver_byte(ret) & DRIVER_SENSE)
5109                         scsi_print_sense_hdr(sdp, NULL, &sshdr);
5110         }
5111
5112         if (!ret)
5113                 hba->curr_dev_pwr_mode = pwr_mode;
5114 out:
5115         scsi_device_put(sdp);
5116         hba->host->eh_noresume = 0;
5117         return ret;
5118 }
5119
5120 static int ufshcd_link_state_transition(struct ufs_hba *hba,
5121                                         enum uic_link_state req_link_state,
5122                                         int check_for_bkops)
5123 {
5124         int ret = 0;
5125
5126         if (req_link_state == hba->uic_link_state)
5127                 return 0;
5128
5129         if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5130                 ret = ufshcd_uic_hibern8_enter(hba);
5131                 if (!ret)
5132                         ufshcd_set_link_hibern8(hba);
5133                 else
5134                         goto out;
5135         }
5136         /*
5137          * If autobkops is enabled, link can't be turned off because
5138          * turning off the link would also turn off the device.
5139          */
5140         else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5141                    (!check_for_bkops || (check_for_bkops &&
5142                     !hba->auto_bkops_enabled))) {
5143                 /*
5144                  * Change controller state to "reset state" which
5145                  * should also put the link in off/reset state
5146                  */
5147                 ufshcd_hba_stop(hba, true);
5148                 /*
5149                  * TODO: Check if we need any delay to make sure that
5150                  * controller is reset
5151                  */
5152                 ufshcd_set_link_off(hba);
5153         }
5154
5155 out:
5156         return ret;
5157 }
5158
5159 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5160 {
5161         /*
5162          * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5163          * power.
5164          *
5165          * If UFS device and link is in OFF state, all power supplies (VCC,
5166          * VCCQ, VCCQ2) can be turned off if power on write protect is not
5167          * required. If UFS link is inactive (Hibern8 or OFF state) and device
5168          * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5169          *
5170          * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5171          * in low power state which would save some power.
5172          */
5173         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5174             !hba->dev_info.is_lu_power_on_wp) {
5175                 ufshcd_setup_vreg(hba, false);
5176         } else if (!ufshcd_is_ufs_dev_active(hba)) {
5177                 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5178                 if (!ufshcd_is_link_active(hba)) {
5179                         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5180                         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5181                 }
5182         }
5183 }
5184
5185 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5186 {
5187         int ret = 0;
5188
5189         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5190             !hba->dev_info.is_lu_power_on_wp) {
5191                 ret = ufshcd_setup_vreg(hba, true);
5192         } else if (!ufshcd_is_ufs_dev_active(hba)) {
5193                 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5194                 if (!ret && !ufshcd_is_link_active(hba)) {
5195                         ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5196                         if (ret)
5197                                 goto vcc_disable;
5198                         ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5199                         if (ret)
5200                                 goto vccq_lpm;
5201                 }
5202         }
5203         goto out;
5204
5205 vccq_lpm:
5206         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5207 vcc_disable:
5208         ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5209 out:
5210         return ret;
5211 }
5212
5213 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5214 {
5215         if (ufshcd_is_link_off(hba))
5216                 ufshcd_setup_hba_vreg(hba, false);
5217 }
5218
5219 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5220 {
5221         if (ufshcd_is_link_off(hba))
5222                 ufshcd_setup_hba_vreg(hba, true);
5223 }
5224
5225 /**
5226  * ufshcd_suspend - helper function for suspend operations
5227  * @hba: per adapter instance
5228  * @pm_op: desired low power operation type
5229  *
5230  * This function will try to put the UFS device and link into low power
5231  * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5232  * (System PM level).
5233  *
5234  * If this function is called during shutdown, it will make sure that
5235  * both UFS device and UFS link is powered off.
5236  *
5237  * NOTE: UFS device & link must be active before we enter in this function.
5238  *
5239  * Returns 0 for success and non-zero for failure
5240  */
5241 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5242 {
5243         int ret = 0;
5244         enum ufs_pm_level pm_lvl;
5245         enum ufs_dev_pwr_mode req_dev_pwr_mode;
5246         enum uic_link_state req_link_state;
5247
5248         hba->pm_op_in_progress = 1;
5249         if (!ufshcd_is_shutdown_pm(pm_op)) {
5250                 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5251                          hba->rpm_lvl : hba->spm_lvl;
5252                 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5253                 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5254         } else {
5255                 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5256                 req_link_state = UIC_LINK_OFF_STATE;
5257         }
5258
5259         /*
5260          * If we can't transition into any of the low power modes
5261          * just gate the clocks.
5262          */
5263         ufshcd_hold(hba, false);
5264         hba->clk_gating.is_suspended = true;
5265
5266         if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5267                         req_link_state == UIC_LINK_ACTIVE_STATE) {
5268                 goto disable_clks;
5269         }
5270
5271         if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5272             (req_link_state == hba->uic_link_state))
5273                 goto out;
5274
5275         /* UFS device & link must be active before we enter in this function */
5276         if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5277                 ret = -EINVAL;
5278                 goto out;
5279         }
5280
5281         if (ufshcd_is_runtime_pm(pm_op)) {
5282                 if (ufshcd_can_autobkops_during_suspend(hba)) {
5283                         /*
5284                          * The device is idle with no requests in the queue,
5285                          * allow background operations if bkops status shows
5286                          * that performance might be impacted.
5287                          */
5288                         ret = ufshcd_urgent_bkops(hba);
5289                         if (ret)
5290                                 goto enable_gating;
5291                 } else {
5292                         /* make sure that auto bkops is disabled */
5293                         ufshcd_disable_auto_bkops(hba);
5294                 }
5295         }
5296
5297         if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5298              ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5299                !ufshcd_is_runtime_pm(pm_op))) {
5300                 /* ensure that bkops is disabled */
5301                 ufshcd_disable_auto_bkops(hba);
5302                 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5303                 if (ret)
5304                         goto enable_gating;
5305         }
5306
5307         ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5308         if (ret)
5309                 goto set_dev_active;
5310
5311         ufshcd_vreg_set_lpm(hba);
5312
5313 disable_clks:
5314         /*
5315          * The clock scaling needs access to controller registers. Hence, Wait
5316          * for pending clock scaling work to be done before clocks are
5317          * turned off.
5318          */
5319         if (ufshcd_is_clkscaling_enabled(hba)) {
5320                 devfreq_suspend_device(hba->devfreq);
5321                 hba->clk_scaling.window_start_t = 0;
5322         }
5323         /*
5324          * Call vendor specific suspend callback. As these callbacks may access
5325          * vendor specific host controller register space call them before the
5326          * host clocks are ON.
5327          */
5328         ret = ufshcd_vops_suspend(hba, pm_op);
5329         if (ret)
5330                 goto set_link_active;
5331
5332         ret = ufshcd_vops_setup_clocks(hba, false);
5333         if (ret)
5334                 goto vops_resume;
5335
5336         if (!ufshcd_is_link_active(hba))
5337                 ufshcd_setup_clocks(hba, false);
5338         else
5339                 /* If link is active, device ref_clk can't be switched off */
5340                 __ufshcd_setup_clocks(hba, false, true);
5341
5342         hba->clk_gating.state = CLKS_OFF;
5343         /*
5344          * Disable the host irq as host controller as there won't be any
5345          * host controller transaction expected till resume.
5346          */
5347         ufshcd_disable_irq(hba);
5348         /* Put the host controller in low power mode if possible */
5349         ufshcd_hba_vreg_set_lpm(hba);
5350         goto out;
5351
5352 vops_resume:
5353         ufshcd_vops_resume(hba, pm_op);
5354 set_link_active:
5355         ufshcd_vreg_set_hpm(hba);
5356         if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5357                 ufshcd_set_link_active(hba);
5358         else if (ufshcd_is_link_off(hba))
5359                 ufshcd_host_reset_and_restore(hba);
5360 set_dev_active:
5361         if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5362                 ufshcd_disable_auto_bkops(hba);
5363 enable_gating:
5364         hba->clk_gating.is_suspended = false;
5365         ufshcd_release(hba);
5366 out:
5367         hba->pm_op_in_progress = 0;
5368         return ret;
5369 }
5370
5371 /**
5372  * ufshcd_resume - helper function for resume operations
5373  * @hba: per adapter instance
5374  * @pm_op: runtime PM or system PM
5375  *
5376  * This function basically brings the UFS device, UniPro link and controller
5377  * to active state.
5378  *
5379  * Returns 0 for success and non-zero for failure
5380  */
5381 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5382 {
5383         int ret;
5384         enum uic_link_state old_link_state;
5385
5386         hba->pm_op_in_progress = 1;
5387         old_link_state = hba->uic_link_state;
5388
5389         ufshcd_hba_vreg_set_hpm(hba);
5390         /* Make sure clocks are enabled before accessing controller */
5391         ret = ufshcd_setup_clocks(hba, true);
5392         if (ret)
5393                 goto out;
5394
5395         /* enable the host irq as host controller would be active soon */
5396         ret = ufshcd_enable_irq(hba);
5397         if (ret)
5398                 goto disable_irq_and_vops_clks;
5399
5400         ret = ufshcd_vreg_set_hpm(hba);
5401         if (ret)
5402                 goto disable_irq_and_vops_clks;
5403
5404         /*
5405          * Call vendor specific resume callback. As these callbacks may access
5406          * vendor specific host controller register space call them when the
5407          * host clocks are ON.
5408          */
5409         ret = ufshcd_vops_resume(hba, pm_op);
5410         if (ret)
5411                 goto disable_vreg;
5412
5413         if (ufshcd_is_link_hibern8(hba)) {
5414                 ret = ufshcd_uic_hibern8_exit(hba);
5415                 if (!ret)
5416                         ufshcd_set_link_active(hba);
5417                 else
5418                         goto vendor_suspend;
5419         } else if (ufshcd_is_link_off(hba)) {
5420                 ret = ufshcd_host_reset_and_restore(hba);
5421                 /*
5422                  * ufshcd_host_reset_and_restore() should have already
5423                  * set the link state as active
5424                  */
5425                 if (ret || !ufshcd_is_link_active(hba))
5426                         goto vendor_suspend;
5427         }
5428
5429         if (!ufshcd_is_ufs_dev_active(hba)) {
5430                 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5431                 if (ret)
5432                         goto set_old_link_state;
5433         }
5434
5435         /*
5436          * If BKOPs operations are urgently needed at this moment then
5437          * keep auto-bkops enabled or else disable it.
5438          */
5439         ufshcd_urgent_bkops(hba);
5440         hba->clk_gating.is_suspended = false;
5441
5442         if (ufshcd_is_clkscaling_enabled(hba))
5443                 devfreq_resume_device(hba->devfreq);
5444
5445         /* Schedule clock gating in case of no access to UFS device yet */
5446         ufshcd_release(hba);
5447         goto out;
5448
5449 set_old_link_state:
5450         ufshcd_link_state_transition(hba, old_link_state, 0);
5451 vendor_suspend:
5452         ufshcd_vops_suspend(hba, pm_op);
5453 disable_vreg:
5454         ufshcd_vreg_set_lpm(hba);
5455 disable_irq_and_vops_clks:
5456         ufshcd_disable_irq(hba);
5457         ufshcd_setup_clocks(hba, false);
5458 out:
5459         hba->pm_op_in_progress = 0;
5460         return ret;
5461 }
5462
5463 /**
5464  * ufshcd_system_suspend - system suspend routine
5465  * @hba: per adapter instance
5466  * @pm_op: runtime PM or system PM
5467  *
5468  * Check the description of ufshcd_suspend() function for more details.
5469  *
5470  * Returns 0 for success and non-zero for failure
5471  */
5472 int ufshcd_system_suspend(struct ufs_hba *hba)
5473 {
5474         int ret = 0;
5475
5476         if (!hba || !hba->is_powered)
5477                 return 0;
5478
5479         if (pm_runtime_suspended(hba->dev)) {
5480                 if (hba->rpm_lvl == hba->spm_lvl)
5481                         /*
5482                          * There is possibility that device may still be in
5483                          * active state during the runtime suspend.
5484                          */
5485                         if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5486                             hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5487                                 goto out;
5488
5489                 /*
5490                  * UFS device and/or UFS link low power states during runtime
5491                  * suspend seems to be different than what is expected during
5492                  * system suspend. Hence runtime resume the devic & link and
5493                  * let the system suspend low power states to take effect.
5494                  * TODO: If resume takes longer time, we might have optimize
5495                  * it in future by not resuming everything if possible.
5496                  */
5497                 ret = ufshcd_runtime_resume(hba);
5498                 if (ret)
5499                         goto out;
5500         }
5501
5502         ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5503 out:
5504         if (!ret)
5505                 hba->is_sys_suspended = true;
5506         return ret;
5507 }
5508 EXPORT_SYMBOL(ufshcd_system_suspend);
5509
5510 /**
5511  * ufshcd_system_resume - system resume routine
5512  * @hba: per adapter instance
5513  *
5514  * Returns 0 for success and non-zero for failure
5515  */
5516
5517 int ufshcd_system_resume(struct ufs_hba *hba)
5518 {
5519         if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5520                 /*
5521                  * Let the runtime resume take care of resuming
5522                  * if runtime suspended.
5523                  */
5524                 return 0;
5525
5526         return ufshcd_resume(hba, UFS_SYSTEM_PM);
5527 }
5528 EXPORT_SYMBOL(ufshcd_system_resume);
5529
5530 /**
5531  * ufshcd_runtime_suspend - runtime suspend routine
5532  * @hba: per adapter instance
5533  *
5534  * Check the description of ufshcd_suspend() function for more details.
5535  *
5536  * Returns 0 for success and non-zero for failure
5537  */
5538 int ufshcd_runtime_suspend(struct ufs_hba *hba)
5539 {
5540         if (!hba || !hba->is_powered)
5541                 return 0;
5542
5543         return ufshcd_suspend(hba, UFS_RUNTIME_PM);
5544 }
5545 EXPORT_SYMBOL(ufshcd_runtime_suspend);
5546
5547 /**
5548  * ufshcd_runtime_resume - runtime resume routine
5549  * @hba: per adapter instance
5550  *
5551  * This function basically brings the UFS device, UniPro link and controller
5552  * to active state. Following operations are done in this function:
5553  *
5554  * 1. Turn on all the controller related clocks
5555  * 2. Bring the UniPro link out of Hibernate state
5556  * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5557  *    to active state.
5558  * 4. If auto-bkops is enabled on the device, disable it.
5559  *
5560  * So following would be the possible power state after this function return
5561  * successfully:
5562  *      S1: UFS device in Active state with VCC rail ON
5563  *          UniPro link in Active state
5564  *          All the UFS/UniPro controller clocks are ON
5565  *
5566  * Returns 0 for success and non-zero for failure
5567  */
5568 int ufshcd_runtime_resume(struct ufs_hba *hba)
5569 {
5570         if (!hba || !hba->is_powered)
5571                 return 0;
5572         else
5573                 return ufshcd_resume(hba, UFS_RUNTIME_PM);
5574 }
5575 EXPORT_SYMBOL(ufshcd_runtime_resume);
5576
5577 int ufshcd_runtime_idle(struct ufs_hba *hba)
5578 {
5579         return 0;
5580 }
5581 EXPORT_SYMBOL(ufshcd_runtime_idle);
5582
5583 /**
5584  * ufshcd_shutdown - shutdown routine
5585  * @hba: per adapter instance
5586  *
5587  * This function would power off both UFS device and UFS link.
5588  *
5589  * Returns 0 always to allow force shutdown even in case of errors.
5590  */
5591 int ufshcd_shutdown(struct ufs_hba *hba)
5592 {
5593         int ret = 0;
5594
5595         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5596                 goto out;
5597
5598         if (pm_runtime_suspended(hba->dev)) {
5599                 ret = ufshcd_runtime_resume(hba);
5600                 if (ret)
5601                         goto out;
5602         }
5603
5604         ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5605 out:
5606         if (ret)
5607                 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5608         /* allow force shutdown even in case of errors */
5609         return 0;
5610 }
5611 EXPORT_SYMBOL(ufshcd_shutdown);
5612
5613 /**
5614  * ufshcd_remove - de-allocate SCSI host and host memory space
5615  *              data structure memory
5616  * @hba - per adapter instance
5617  */
5618 void ufshcd_remove(struct ufs_hba *hba)
5619 {
5620         scsi_remove_host(hba->host);
5621         /* disable interrupts */
5622         ufshcd_disable_intr(hba, hba->intr_mask);
5623         ufshcd_hba_stop(hba, true);
5624
5625         scsi_host_put(hba->host);
5626
5627         ufshcd_exit_clk_gating(hba);
5628         if (ufshcd_is_clkscaling_enabled(hba))
5629                 devfreq_remove_device(hba->devfreq);
5630         ufshcd_hba_exit(hba);
5631 }
5632 EXPORT_SYMBOL_GPL(ufshcd_remove);
5633
5634 /**
5635  * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
5636  * @hba: pointer to Host Bus Adapter (HBA)
5637  */
5638 void ufshcd_dealloc_host(struct ufs_hba *hba)
5639 {
5640         scsi_host_put(hba->host);
5641 }
5642 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
5643
5644 /**
5645  * ufshcd_set_dma_mask - Set dma mask based on the controller
5646  *                       addressing capability
5647  * @hba: per adapter instance
5648  *
5649  * Returns 0 for success, non-zero for failure
5650  */
5651 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
5652 {
5653         if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
5654                 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
5655                         return 0;
5656         }
5657         return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
5658 }
5659
5660 /**
5661  * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
5662  * @dev: pointer to device handle
5663  * @hba_handle: driver private handle
5664  * Returns 0 on success, non-zero value on failure
5665  */
5666 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
5667 {
5668         struct Scsi_Host *host;
5669         struct ufs_hba *hba;
5670         int err = 0;
5671
5672         if (!dev) {
5673                 dev_err(dev,
5674                 "Invalid memory reference for dev is NULL\n");
5675                 err = -ENODEV;
5676                 goto out_error;
5677         }
5678
5679         host = scsi_host_alloc(&ufshcd_driver_template,
5680                                 sizeof(struct ufs_hba));
5681         if (!host) {
5682                 dev_err(dev, "scsi_host_alloc failed\n");
5683                 err = -ENOMEM;
5684                 goto out_error;
5685         }
5686         hba = shost_priv(host);
5687         hba->host = host;
5688         hba->dev = dev;
5689         *hba_handle = hba;
5690
5691 out_error:
5692         return err;
5693 }
5694 EXPORT_SYMBOL(ufshcd_alloc_host);
5695
5696 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
5697 {
5698         int ret = 0;
5699         struct ufs_clk_info *clki;
5700         struct list_head *head = &hba->clk_list_head;
5701
5702         if (!head || list_empty(head))
5703                 goto out;
5704
5705         ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
5706         if (ret)
5707                 return ret;
5708
5709         list_for_each_entry(clki, head, list) {
5710                 if (!IS_ERR_OR_NULL(clki->clk)) {
5711                         if (scale_up && clki->max_freq) {
5712                                 if (clki->curr_freq == clki->max_freq)
5713                                         continue;
5714                                 ret = clk_set_rate(clki->clk, clki->max_freq);
5715                                 if (ret) {
5716                                         dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5717                                                 __func__, clki->name,
5718                                                 clki->max_freq, ret);
5719                                         break;
5720                                 }
5721                                 clki->curr_freq = clki->max_freq;
5722
5723                         } else if (!scale_up && clki->min_freq) {
5724                                 if (clki->curr_freq == clki->min_freq)
5725                                         continue;
5726                                 ret = clk_set_rate(clki->clk, clki->min_freq);
5727                                 if (ret) {
5728                                         dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5729                                                 __func__, clki->name,
5730                                                 clki->min_freq, ret);
5731                                         break;
5732                                 }
5733                                 clki->curr_freq = clki->min_freq;
5734                         }
5735                 }
5736                 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
5737                                 clki->name, clk_get_rate(clki->clk));
5738         }
5739
5740         ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
5741
5742 out:
5743         return ret;
5744 }
5745
5746 static int ufshcd_devfreq_target(struct device *dev,
5747                                 unsigned long *freq, u32 flags)
5748 {
5749         int err = 0;
5750         struct ufs_hba *hba = dev_get_drvdata(dev);
5751
5752         if (!ufshcd_is_clkscaling_enabled(hba))
5753                 return -EINVAL;
5754
5755         if (*freq == UINT_MAX)
5756                 err = ufshcd_scale_clks(hba, true);
5757         else if (*freq == 0)
5758                 err = ufshcd_scale_clks(hba, false);
5759
5760         return err;
5761 }
5762
5763 static int ufshcd_devfreq_get_dev_status(struct device *dev,
5764                 struct devfreq_dev_status *stat)
5765 {
5766         struct ufs_hba *hba = dev_get_drvdata(dev);
5767         struct ufs_clk_scaling *scaling = &hba->clk_scaling;
5768         unsigned long flags;
5769
5770         if (!ufshcd_is_clkscaling_enabled(hba))
5771                 return -EINVAL;
5772
5773         memset(stat, 0, sizeof(*stat));
5774
5775         spin_lock_irqsave(hba->host->host_lock, flags);
5776         if (!scaling->window_start_t)
5777                 goto start_window;
5778
5779         if (scaling->is_busy_started)
5780                 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
5781                                         scaling->busy_start_t));
5782
5783         stat->total_time = jiffies_to_usecs((long)jiffies -
5784                                 (long)scaling->window_start_t);
5785         stat->busy_time = scaling->tot_busy_t;
5786 start_window:
5787         scaling->window_start_t = jiffies;
5788         scaling->tot_busy_t = 0;
5789
5790         if (hba->outstanding_reqs) {
5791                 scaling->busy_start_t = ktime_get();
5792                 scaling->is_busy_started = true;
5793         } else {
5794                 scaling->busy_start_t = ktime_set(0, 0);
5795                 scaling->is_busy_started = false;
5796         }
5797         spin_unlock_irqrestore(hba->host->host_lock, flags);
5798         return 0;
5799 }
5800
5801 static struct devfreq_dev_profile ufs_devfreq_profile = {
5802         .polling_ms     = 100,
5803         .target         = ufshcd_devfreq_target,
5804         .get_dev_status = ufshcd_devfreq_get_dev_status,
5805 };
5806
5807 /**
5808  * ufshcd_init - Driver initialization routine
5809  * @hba: per-adapter instance
5810  * @mmio_base: base register address
5811  * @irq: Interrupt line of device
5812  * Returns 0 on success, non-zero value on failure
5813  */
5814 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
5815 {
5816         int err;
5817         struct Scsi_Host *host = hba->host;
5818         struct device *dev = hba->dev;
5819
5820         if (!mmio_base) {
5821                 dev_err(hba->dev,
5822                 "Invalid memory reference for mmio_base is NULL\n");
5823                 err = -ENODEV;
5824                 goto out_error;
5825         }
5826
5827         hba->mmio_base = mmio_base;
5828         hba->irq = irq;
5829
5830         err = ufshcd_hba_init(hba);
5831         if (err)
5832                 goto out_error;
5833
5834         /* Read capabilities registers */
5835         ufshcd_hba_capabilities(hba);
5836
5837         /* Get UFS version supported by the controller */
5838         hba->ufs_version = ufshcd_get_ufs_version(hba);
5839
5840         /* Get Interrupt bit mask per version */
5841         hba->intr_mask = ufshcd_get_intr_mask(hba);
5842
5843         err = ufshcd_set_dma_mask(hba);
5844         if (err) {
5845                 dev_err(hba->dev, "set dma mask failed\n");
5846                 goto out_disable;
5847         }
5848
5849         /* Allocate memory for host memory space */
5850         err = ufshcd_memory_alloc(hba);
5851         if (err) {
5852                 dev_err(hba->dev, "Memory allocation failed\n");
5853                 goto out_disable;
5854         }
5855
5856         /* Configure LRB */
5857         ufshcd_host_memory_configure(hba);
5858
5859         host->can_queue = hba->nutrs;
5860         host->cmd_per_lun = hba->nutrs;
5861         host->max_id = UFSHCD_MAX_ID;
5862         host->max_lun = UFS_MAX_LUNS;
5863         host->max_channel = UFSHCD_MAX_CHANNEL;
5864         host->unique_id = host->host_no;
5865         host->max_cmd_len = MAX_CDB_SIZE;
5866
5867         hba->max_pwr_info.is_valid = false;
5868
5869         /* Initailize wait queue for task management */
5870         init_waitqueue_head(&hba->tm_wq);
5871         init_waitqueue_head(&hba->tm_tag_wq);
5872
5873         /* Initialize work queues */
5874         INIT_WORK(&hba->eh_work, ufshcd_err_handler);
5875         INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
5876
5877         /* Initialize UIC command mutex */
5878         mutex_init(&hba->uic_cmd_mutex);
5879
5880         /* Initialize mutex for device management commands */
5881         mutex_init(&hba->dev_cmd.lock);
5882
5883         /* Initialize device management tag acquire wait queue */
5884         init_waitqueue_head(&hba->dev_cmd.tag_wq);
5885
5886         ufshcd_init_clk_gating(hba);
5887
5888         /*
5889          * In order to avoid any spurious interrupt immediately after
5890          * registering UFS controller interrupt handler, clear any pending UFS
5891          * interrupt status and disable all the UFS interrupts.
5892          */
5893         ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
5894                       REG_INTERRUPT_STATUS);
5895         ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
5896         /*
5897          * Make sure that UFS interrupts are disabled and any pending interrupt
5898          * status is cleared before registering UFS interrupt handler.
5899          */
5900         mb();
5901
5902         /* IRQ registration */
5903         err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
5904         if (err) {
5905                 dev_err(hba->dev, "request irq failed\n");
5906                 goto exit_gating;
5907         } else {
5908                 hba->is_irq_enabled = true;
5909         }
5910
5911         err = scsi_add_host(host, hba->dev);
5912         if (err) {
5913                 dev_err(hba->dev, "scsi_add_host failed\n");
5914                 goto exit_gating;
5915         }
5916
5917         /* Host controller enable */
5918         err = ufshcd_hba_enable(hba);
5919         if (err) {
5920                 dev_err(hba->dev, "Host controller enable failed\n");
5921                 goto out_remove_scsi_host;
5922         }
5923
5924         if (ufshcd_is_clkscaling_enabled(hba)) {
5925                 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
5926                                                    "simple_ondemand", NULL);
5927                 if (IS_ERR(hba->devfreq)) {
5928                         dev_err(hba->dev, "Unable to register with devfreq %ld\n",
5929                                         PTR_ERR(hba->devfreq));
5930                         goto out_remove_scsi_host;
5931                 }
5932                 /* Suspend devfreq until the UFS device is detected */
5933                 devfreq_suspend_device(hba->devfreq);
5934                 hba->clk_scaling.window_start_t = 0;
5935         }
5936
5937         /* Hold auto suspend until async scan completes */
5938         pm_runtime_get_sync(dev);
5939
5940         /*
5941          * The device-initialize-sequence hasn't been invoked yet.
5942          * Set the device to power-off state
5943          */
5944         ufshcd_set_ufs_dev_poweroff(hba);
5945
5946         async_schedule(ufshcd_async_scan, hba);
5947
5948         return 0;
5949
5950 out_remove_scsi_host:
5951         scsi_remove_host(hba->host);
5952 exit_gating:
5953         ufshcd_exit_clk_gating(hba);
5954 out_disable:
5955         hba->is_irq_enabled = false;
5956         scsi_host_put(host);
5957         ufshcd_hba_exit(hba);
5958 out_error:
5959         return err;
5960 }
5961 EXPORT_SYMBOL_GPL(ufshcd_init);
5962
5963 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
5964 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
5965 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
5966 MODULE_LICENSE("GPL");
5967 MODULE_VERSION(UFSHCD_DRIVER_VERSION);