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