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