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