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