OSDN Git Service

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