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