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