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