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