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