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