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