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