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