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