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