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