OSDN Git Service

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