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