OSDN Git Service

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