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