Merge tag 'xtensa-20210429' of git://github.com/jcmvbkbc/linux-xtensa
[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: time in seconds
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
2876         init_completion(&wait);
2877         lrbp = &hba->lrb[tag];
2878         if (unlikely(lrbp->in_use)) {
2879                 err = -EBUSY;
2880                 goto out;
2881         }
2882
2883         WARN_ON(lrbp->cmd);
2884         err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2885         if (unlikely(err))
2886                 goto out_put_tag;
2887
2888         hba->dev_cmd.complete = &wait;
2889
2890         ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2891         /* Make sure descriptors are ready before ringing the doorbell */
2892         wmb();
2893         spin_lock_irqsave(hba->host->host_lock, flags);
2894         ufshcd_send_command(hba, tag);
2895         spin_unlock_irqrestore(hba->host->host_lock, flags);
2896
2897         err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2898
2899 out:
2900         ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2901                                     (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2902
2903 out_put_tag:
2904         blk_put_request(req);
2905 out_unlock:
2906         up_read(&hba->clk_scaling_lock);
2907         return err;
2908 }
2909
2910 /**
2911  * ufshcd_init_query() - init the query response and request parameters
2912  * @hba: per-adapter instance
2913  * @request: address of the request pointer to be initialized
2914  * @response: address of the response pointer to be initialized
2915  * @opcode: operation to perform
2916  * @idn: flag idn to access
2917  * @index: LU number to access
2918  * @selector: query/flag/descriptor further identification
2919  */
2920 static inline void ufshcd_init_query(struct ufs_hba *hba,
2921                 struct ufs_query_req **request, struct ufs_query_res **response,
2922                 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2923 {
2924         *request = &hba->dev_cmd.query.request;
2925         *response = &hba->dev_cmd.query.response;
2926         memset(*request, 0, sizeof(struct ufs_query_req));
2927         memset(*response, 0, sizeof(struct ufs_query_res));
2928         (*request)->upiu_req.opcode = opcode;
2929         (*request)->upiu_req.idn = idn;
2930         (*request)->upiu_req.index = index;
2931         (*request)->upiu_req.selector = selector;
2932 }
2933
2934 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2935         enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2936 {
2937         int ret;
2938         int retries;
2939
2940         for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2941                 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2942                 if (ret)
2943                         dev_dbg(hba->dev,
2944                                 "%s: failed with error %d, retries %d\n",
2945                                 __func__, ret, retries);
2946                 else
2947                         break;
2948         }
2949
2950         if (ret)
2951                 dev_err(hba->dev,
2952                         "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2953                         __func__, opcode, idn, ret, retries);
2954         return ret;
2955 }
2956
2957 /**
2958  * ufshcd_query_flag() - API function for sending flag query requests
2959  * @hba: per-adapter instance
2960  * @opcode: flag query to perform
2961  * @idn: flag idn to access
2962  * @index: flag index to access
2963  * @flag_res: the flag value after the query request completes
2964  *
2965  * Returns 0 for success, non-zero in case of failure
2966  */
2967 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2968                         enum flag_idn idn, u8 index, bool *flag_res)
2969 {
2970         struct ufs_query_req *request = NULL;
2971         struct ufs_query_res *response = NULL;
2972         int err, selector = 0;
2973         int timeout = QUERY_REQ_TIMEOUT;
2974
2975         BUG_ON(!hba);
2976
2977         ufshcd_hold(hba, false);
2978         mutex_lock(&hba->dev_cmd.lock);
2979         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2980                         selector);
2981
2982         switch (opcode) {
2983         case UPIU_QUERY_OPCODE_SET_FLAG:
2984         case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2985         case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2986                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2987                 break;
2988         case UPIU_QUERY_OPCODE_READ_FLAG:
2989                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2990                 if (!flag_res) {
2991                         /* No dummy reads */
2992                         dev_err(hba->dev, "%s: Invalid argument for read request\n",
2993                                         __func__);
2994                         err = -EINVAL;
2995                         goto out_unlock;
2996                 }
2997                 break;
2998         default:
2999                 dev_err(hba->dev,
3000                         "%s: Expected query flag opcode but got = %d\n",
3001                         __func__, opcode);
3002                 err = -EINVAL;
3003                 goto out_unlock;
3004         }
3005
3006         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3007
3008         if (err) {
3009                 dev_err(hba->dev,
3010                         "%s: Sending flag query for idn %d failed, err = %d\n",
3011                         __func__, idn, err);
3012                 goto out_unlock;
3013         }
3014
3015         if (flag_res)
3016                 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3017                                 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3018
3019 out_unlock:
3020         mutex_unlock(&hba->dev_cmd.lock);
3021         ufshcd_release(hba);
3022         return err;
3023 }
3024
3025 /**
3026  * ufshcd_query_attr - API function for sending attribute requests
3027  * @hba: per-adapter instance
3028  * @opcode: attribute opcode
3029  * @idn: attribute idn to access
3030  * @index: index field
3031  * @selector: selector field
3032  * @attr_val: the attribute value after the query request completes
3033  *
3034  * Returns 0 for success, non-zero in case of failure
3035 */
3036 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3037                       enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3038 {
3039         struct ufs_query_req *request = NULL;
3040         struct ufs_query_res *response = NULL;
3041         int err;
3042
3043         BUG_ON(!hba);
3044
3045         if (!attr_val) {
3046                 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3047                                 __func__, opcode);
3048                 return -EINVAL;
3049         }
3050
3051         ufshcd_hold(hba, false);
3052
3053         mutex_lock(&hba->dev_cmd.lock);
3054         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3055                         selector);
3056
3057         switch (opcode) {
3058         case UPIU_QUERY_OPCODE_WRITE_ATTR:
3059                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3060                 request->upiu_req.value = cpu_to_be32(*attr_val);
3061                 break;
3062         case UPIU_QUERY_OPCODE_READ_ATTR:
3063                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3064                 break;
3065         default:
3066                 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3067                                 __func__, opcode);
3068                 err = -EINVAL;
3069                 goto out_unlock;
3070         }
3071
3072         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3073
3074         if (err) {
3075                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3076                                 __func__, opcode, idn, index, err);
3077                 goto out_unlock;
3078         }
3079
3080         *attr_val = be32_to_cpu(response->upiu_res.value);
3081
3082 out_unlock:
3083         mutex_unlock(&hba->dev_cmd.lock);
3084         ufshcd_release(hba);
3085         return err;
3086 }
3087
3088 /**
3089  * ufshcd_query_attr_retry() - API function for sending query
3090  * attribute with retries
3091  * @hba: per-adapter instance
3092  * @opcode: attribute opcode
3093  * @idn: attribute idn to access
3094  * @index: index field
3095  * @selector: selector field
3096  * @attr_val: the attribute value after the query request
3097  * completes
3098  *
3099  * Returns 0 for success, non-zero in case of failure
3100 */
3101 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3102         enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3103         u32 *attr_val)
3104 {
3105         int ret = 0;
3106         u32 retries;
3107
3108         for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3109                 ret = ufshcd_query_attr(hba, opcode, idn, index,
3110                                                 selector, attr_val);
3111                 if (ret)
3112                         dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3113                                 __func__, ret, retries);
3114                 else
3115                         break;
3116         }
3117
3118         if (ret)
3119                 dev_err(hba->dev,
3120                         "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3121                         __func__, idn, ret, QUERY_REQ_RETRIES);
3122         return ret;
3123 }
3124
3125 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3126                         enum query_opcode opcode, enum desc_idn idn, u8 index,
3127                         u8 selector, u8 *desc_buf, int *buf_len)
3128 {
3129         struct ufs_query_req *request = NULL;
3130         struct ufs_query_res *response = NULL;
3131         int err;
3132
3133         BUG_ON(!hba);
3134
3135         if (!desc_buf) {
3136                 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3137                                 __func__, opcode);
3138                 return -EINVAL;
3139         }
3140
3141         if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3142                 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3143                                 __func__, *buf_len);
3144                 return -EINVAL;
3145         }
3146
3147         ufshcd_hold(hba, false);
3148
3149         mutex_lock(&hba->dev_cmd.lock);
3150         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3151                         selector);
3152         hba->dev_cmd.query.descriptor = desc_buf;
3153         request->upiu_req.length = cpu_to_be16(*buf_len);
3154
3155         switch (opcode) {
3156         case UPIU_QUERY_OPCODE_WRITE_DESC:
3157                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3158                 break;
3159         case UPIU_QUERY_OPCODE_READ_DESC:
3160                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3161                 break;
3162         default:
3163                 dev_err(hba->dev,
3164                                 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3165                                 __func__, opcode);
3166                 err = -EINVAL;
3167                 goto out_unlock;
3168         }
3169
3170         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3171
3172         if (err) {
3173                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3174                                 __func__, opcode, idn, index, err);
3175                 goto out_unlock;
3176         }
3177
3178         *buf_len = be16_to_cpu(response->upiu_res.length);
3179
3180 out_unlock:
3181         hba->dev_cmd.query.descriptor = NULL;
3182         mutex_unlock(&hba->dev_cmd.lock);
3183         ufshcd_release(hba);
3184         return err;
3185 }
3186
3187 /**
3188  * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3189  * @hba: per-adapter instance
3190  * @opcode: attribute opcode
3191  * @idn: attribute idn to access
3192  * @index: index field
3193  * @selector: selector field
3194  * @desc_buf: the buffer that contains the descriptor
3195  * @buf_len: length parameter passed to the device
3196  *
3197  * Returns 0 for success, non-zero in case of failure.
3198  * The buf_len parameter will contain, on return, the length parameter
3199  * received on the response.
3200  */
3201 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3202                                   enum query_opcode opcode,
3203                                   enum desc_idn idn, u8 index,
3204                                   u8 selector,
3205                                   u8 *desc_buf, int *buf_len)
3206 {
3207         int err;
3208         int retries;
3209
3210         for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3211                 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3212                                                 selector, desc_buf, buf_len);
3213                 if (!err || err == -EINVAL)
3214                         break;
3215         }
3216
3217         return err;
3218 }
3219
3220 /**
3221  * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3222  * @hba: Pointer to adapter instance
3223  * @desc_id: descriptor idn value
3224  * @desc_len: mapped desc length (out)
3225  */
3226 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3227                                   int *desc_len)
3228 {
3229         if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3230             desc_id == QUERY_DESC_IDN_RFU_1)
3231                 *desc_len = 0;
3232         else
3233                 *desc_len = hba->desc_size[desc_id];
3234 }
3235 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3236
3237 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3238                                       enum desc_idn desc_id, int desc_index,
3239                                       unsigned char desc_len)
3240 {
3241         if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3242             desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3243                 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3244                  * than the RPMB unit, however, both descriptors share the same
3245                  * desc_idn, to cover both unit descriptors with one length, we
3246                  * choose the normal unit descriptor length by desc_index.
3247                  */
3248                 hba->desc_size[desc_id] = desc_len;
3249 }
3250
3251 /**
3252  * ufshcd_read_desc_param - read the specified descriptor parameter
3253  * @hba: Pointer to adapter instance
3254  * @desc_id: descriptor idn value
3255  * @desc_index: descriptor index
3256  * @param_offset: offset of the parameter to read
3257  * @param_read_buf: pointer to buffer where parameter would be read
3258  * @param_size: sizeof(param_read_buf)
3259  *
3260  * Return 0 in case of success, non-zero otherwise
3261  */
3262 int ufshcd_read_desc_param(struct ufs_hba *hba,
3263                            enum desc_idn desc_id,
3264                            int desc_index,
3265                            u8 param_offset,
3266                            u8 *param_read_buf,
3267                            u8 param_size)
3268 {
3269         int ret;
3270         u8 *desc_buf;
3271         int buff_len;
3272         bool is_kmalloc = true;
3273
3274         /* Safety check */
3275         if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3276                 return -EINVAL;
3277
3278         /* Get the length of descriptor */
3279         ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3280         if (!buff_len) {
3281                 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3282                 return -EINVAL;
3283         }
3284
3285         if (param_offset >= buff_len) {
3286                 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3287                         __func__, param_offset, desc_id, buff_len);
3288                 return -EINVAL;
3289         }
3290
3291         /* Check whether we need temp memory */
3292         if (param_offset != 0 || param_size < buff_len) {
3293                 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3294                 if (!desc_buf)
3295                         return -ENOMEM;
3296         } else {
3297                 desc_buf = param_read_buf;
3298                 is_kmalloc = false;
3299         }
3300
3301         /* Request for full descriptor */
3302         ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3303                                         desc_id, desc_index, 0,
3304                                         desc_buf, &buff_len);
3305
3306         if (ret) {
3307                 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3308                         __func__, desc_id, desc_index, param_offset, ret);
3309                 goto out;
3310         }
3311
3312         /* Sanity check */
3313         if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3314                 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3315                         __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3316                 ret = -EINVAL;
3317                 goto out;
3318         }
3319
3320         /* Update descriptor length */
3321         buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3322         ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3323
3324         if (is_kmalloc) {
3325                 /* Make sure we don't copy more data than available */
3326                 if (param_offset + param_size > buff_len)
3327                         param_size = buff_len - param_offset;
3328                 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3329         }
3330 out:
3331         if (is_kmalloc)
3332                 kfree(desc_buf);
3333         return ret;
3334 }
3335
3336 /**
3337  * struct uc_string_id - unicode string
3338  *
3339  * @len: size of this descriptor inclusive
3340  * @type: descriptor type
3341  * @uc: unicode string character
3342  */
3343 struct uc_string_id {
3344         u8 len;
3345         u8 type;
3346         wchar_t uc[];
3347 } __packed;
3348
3349 /* replace non-printable or non-ASCII characters with spaces */
3350 static inline char ufshcd_remove_non_printable(u8 ch)
3351 {
3352         return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3353 }
3354
3355 /**
3356  * ufshcd_read_string_desc - read string descriptor
3357  * @hba: pointer to adapter instance
3358  * @desc_index: descriptor index
3359  * @buf: pointer to buffer where descriptor would be read,
3360  *       the caller should free the memory.
3361  * @ascii: if true convert from unicode to ascii characters
3362  *         null terminated string.
3363  *
3364  * Return:
3365  * *      string size on success.
3366  * *      -ENOMEM: on allocation failure
3367  * *      -EINVAL: on a wrong parameter
3368  */
3369 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3370                             u8 **buf, bool ascii)
3371 {
3372         struct uc_string_id *uc_str;
3373         u8 *str;
3374         int ret;
3375
3376         if (!buf)
3377                 return -EINVAL;
3378
3379         uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3380         if (!uc_str)
3381                 return -ENOMEM;
3382
3383         ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3384                                      (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3385         if (ret < 0) {
3386                 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3387                         QUERY_REQ_RETRIES, ret);
3388                 str = NULL;
3389                 goto out;
3390         }
3391
3392         if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3393                 dev_dbg(hba->dev, "String Desc is of zero length\n");
3394                 str = NULL;
3395                 ret = 0;
3396                 goto out;
3397         }
3398
3399         if (ascii) {
3400                 ssize_t ascii_len;
3401                 int i;
3402                 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3403                 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3404                 str = kzalloc(ascii_len, GFP_KERNEL);
3405                 if (!str) {
3406                         ret = -ENOMEM;
3407                         goto out;
3408                 }
3409
3410                 /*
3411                  * the descriptor contains string in UTF16 format
3412                  * we need to convert to utf-8 so it can be displayed
3413                  */
3414                 ret = utf16s_to_utf8s(uc_str->uc,
3415                                       uc_str->len - QUERY_DESC_HDR_SIZE,
3416                                       UTF16_BIG_ENDIAN, str, ascii_len);
3417
3418                 /* replace non-printable or non-ASCII characters with spaces */
3419                 for (i = 0; i < ret; i++)
3420                         str[i] = ufshcd_remove_non_printable(str[i]);
3421
3422                 str[ret++] = '\0';
3423
3424         } else {
3425                 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3426                 if (!str) {
3427                         ret = -ENOMEM;
3428                         goto out;
3429                 }
3430                 ret = uc_str->len;
3431         }
3432 out:
3433         *buf = str;
3434         kfree(uc_str);
3435         return ret;
3436 }
3437
3438 /**
3439  * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3440  * @hba: Pointer to adapter instance
3441  * @lun: lun id
3442  * @param_offset: offset of the parameter to read
3443  * @param_read_buf: pointer to buffer where parameter would be read
3444  * @param_size: sizeof(param_read_buf)
3445  *
3446  * Return 0 in case of success, non-zero otherwise
3447  */
3448 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3449                                               int lun,
3450                                               enum unit_desc_param param_offset,
3451                                               u8 *param_read_buf,
3452                                               u32 param_size)
3453 {
3454         /*
3455          * Unit descriptors are only available for general purpose LUs (LUN id
3456          * from 0 to 7) and RPMB Well known LU.
3457          */
3458         if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3459                 return -EOPNOTSUPP;
3460
3461         return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3462                                       param_offset, param_read_buf, param_size);
3463 }
3464
3465 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3466 {
3467         int err = 0;
3468         u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3469
3470         if (hba->dev_info.wspecversion >= 0x300) {
3471                 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3472                                 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3473                                 &gating_wait);
3474                 if (err)
3475                         dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3476                                          err, gating_wait);
3477
3478                 if (gating_wait == 0) {
3479                         gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3480                         dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3481                                          gating_wait);
3482                 }
3483
3484                 hba->dev_info.clk_gating_wait_us = gating_wait;
3485         }
3486
3487         return err;
3488 }
3489
3490 /**
3491  * ufshcd_memory_alloc - allocate memory for host memory space data structures
3492  * @hba: per adapter instance
3493  *
3494  * 1. Allocate DMA memory for Command Descriptor array
3495  *      Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3496  * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3497  * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3498  *      (UTMRDL)
3499  * 4. Allocate memory for local reference block(lrb).
3500  *
3501  * Returns 0 for success, non-zero in case of failure
3502  */
3503 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3504 {
3505         size_t utmrdl_size, utrdl_size, ucdl_size;
3506
3507         /* Allocate memory for UTP command descriptors */
3508         ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3509         hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3510                                                   ucdl_size,
3511                                                   &hba->ucdl_dma_addr,
3512                                                   GFP_KERNEL);
3513
3514         /*
3515          * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3516          * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3517          * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3518          * be aligned to 128 bytes as well
3519          */
3520         if (!hba->ucdl_base_addr ||
3521             WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3522                 dev_err(hba->dev,
3523                         "Command Descriptor Memory allocation failed\n");
3524                 goto out;
3525         }
3526
3527         /*
3528          * Allocate memory for UTP Transfer descriptors
3529          * UFSHCI requires 1024 byte alignment of UTRD
3530          */
3531         utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3532         hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3533                                                    utrdl_size,
3534                                                    &hba->utrdl_dma_addr,
3535                                                    GFP_KERNEL);
3536         if (!hba->utrdl_base_addr ||
3537             WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3538                 dev_err(hba->dev,
3539                         "Transfer Descriptor Memory allocation failed\n");
3540                 goto out;
3541         }
3542
3543         /*
3544          * Allocate memory for UTP Task Management descriptors
3545          * UFSHCI requires 1024 byte alignment of UTMRD
3546          */
3547         utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3548         hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3549                                                     utmrdl_size,
3550                                                     &hba->utmrdl_dma_addr,
3551                                                     GFP_KERNEL);
3552         if (!hba->utmrdl_base_addr ||
3553             WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3554                 dev_err(hba->dev,
3555                 "Task Management Descriptor Memory allocation failed\n");
3556                 goto out;
3557         }
3558
3559         /* Allocate memory for local reference block */
3560         hba->lrb = devm_kcalloc(hba->dev,
3561                                 hba->nutrs, sizeof(struct ufshcd_lrb),
3562                                 GFP_KERNEL);
3563         if (!hba->lrb) {
3564                 dev_err(hba->dev, "LRB Memory allocation failed\n");
3565                 goto out;
3566         }
3567         return 0;
3568 out:
3569         return -ENOMEM;
3570 }
3571
3572 /**
3573  * ufshcd_host_memory_configure - configure local reference block with
3574  *                              memory offsets
3575  * @hba: per adapter instance
3576  *
3577  * Configure Host memory space
3578  * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3579  * address.
3580  * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3581  * and PRDT offset.
3582  * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3583  * into local reference block.
3584  */
3585 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3586 {
3587         struct utp_transfer_req_desc *utrdlp;
3588         dma_addr_t cmd_desc_dma_addr;
3589         dma_addr_t cmd_desc_element_addr;
3590         u16 response_offset;
3591         u16 prdt_offset;
3592         int cmd_desc_size;
3593         int i;
3594
3595         utrdlp = hba->utrdl_base_addr;
3596
3597         response_offset =
3598                 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3599         prdt_offset =
3600                 offsetof(struct utp_transfer_cmd_desc, prd_table);
3601
3602         cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3603         cmd_desc_dma_addr = hba->ucdl_dma_addr;
3604
3605         for (i = 0; i < hba->nutrs; i++) {
3606                 /* Configure UTRD with command descriptor base address */
3607                 cmd_desc_element_addr =
3608                                 (cmd_desc_dma_addr + (cmd_desc_size * i));
3609                 utrdlp[i].command_desc_base_addr_lo =
3610                                 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3611                 utrdlp[i].command_desc_base_addr_hi =
3612                                 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3613
3614                 /* Response upiu and prdt offset should be in double words */
3615                 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3616                         utrdlp[i].response_upiu_offset =
3617                                 cpu_to_le16(response_offset);
3618                         utrdlp[i].prd_table_offset =
3619                                 cpu_to_le16(prdt_offset);
3620                         utrdlp[i].response_upiu_length =
3621                                 cpu_to_le16(ALIGNED_UPIU_SIZE);
3622                 } else {
3623                         utrdlp[i].response_upiu_offset =
3624                                 cpu_to_le16(response_offset >> 2);
3625                         utrdlp[i].prd_table_offset =
3626                                 cpu_to_le16(prdt_offset >> 2);
3627                         utrdlp[i].response_upiu_length =
3628                                 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3629                 }
3630
3631                 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3632         }
3633 }
3634
3635 /**
3636  * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3637  * @hba: per adapter instance
3638  *
3639  * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3640  * in order to initialize the Unipro link startup procedure.
3641  * Once the Unipro links are up, the device connected to the controller
3642  * is detected.
3643  *
3644  * Returns 0 on success, non-zero value on failure
3645  */
3646 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3647 {
3648         struct uic_command uic_cmd = {0};
3649         int ret;
3650
3651         uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3652
3653         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3654         if (ret)
3655                 dev_dbg(hba->dev,
3656                         "dme-link-startup: error code %d\n", ret);
3657         return ret;
3658 }
3659 /**
3660  * ufshcd_dme_reset - UIC command for DME_RESET
3661  * @hba: per adapter instance
3662  *
3663  * DME_RESET command is issued in order to reset UniPro stack.
3664  * This function now deals with cold reset.
3665  *
3666  * Returns 0 on success, non-zero value on failure
3667  */
3668 static int ufshcd_dme_reset(struct ufs_hba *hba)
3669 {
3670         struct uic_command uic_cmd = {0};
3671         int ret;
3672
3673         uic_cmd.command = UIC_CMD_DME_RESET;
3674
3675         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3676         if (ret)
3677                 dev_err(hba->dev,
3678                         "dme-reset: error code %d\n", ret);
3679
3680         return ret;
3681 }
3682
3683 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3684                                int agreed_gear,
3685                                int adapt_val)
3686 {
3687         int ret;
3688
3689         if (agreed_gear != UFS_HS_G4)
3690                 adapt_val = PA_NO_ADAPT;
3691
3692         ret = ufshcd_dme_set(hba,
3693                              UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3694                              adapt_val);
3695         return ret;
3696 }
3697 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3698
3699 /**
3700  * ufshcd_dme_enable - UIC command for DME_ENABLE
3701  * @hba: per adapter instance
3702  *
3703  * DME_ENABLE command is issued in order to enable UniPro stack.
3704  *
3705  * Returns 0 on success, non-zero value on failure
3706  */
3707 static int ufshcd_dme_enable(struct ufs_hba *hba)
3708 {
3709         struct uic_command uic_cmd = {0};
3710         int ret;
3711
3712         uic_cmd.command = UIC_CMD_DME_ENABLE;
3713
3714         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3715         if (ret)
3716                 dev_err(hba->dev,
3717                         "dme-enable: error code %d\n", ret);
3718
3719         return ret;
3720 }
3721
3722 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3723 {
3724         #define MIN_DELAY_BEFORE_DME_CMDS_US    1000
3725         unsigned long min_sleep_time_us;
3726
3727         if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3728                 return;
3729
3730         /*
3731          * last_dme_cmd_tstamp will be 0 only for 1st call to
3732          * this function
3733          */
3734         if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3735                 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3736         } else {
3737                 unsigned long delta =
3738                         (unsigned long) ktime_to_us(
3739                                 ktime_sub(ktime_get(),
3740                                 hba->last_dme_cmd_tstamp));
3741
3742                 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3743                         min_sleep_time_us =
3744                                 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3745                 else
3746                         return; /* no more delay required */
3747         }
3748
3749         /* allow sleep for extra 50us if needed */
3750         usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3751 }
3752
3753 /**
3754  * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3755  * @hba: per adapter instance
3756  * @attr_sel: uic command argument1
3757  * @attr_set: attribute set type as uic command argument2
3758  * @mib_val: setting value as uic command argument3
3759  * @peer: indicate whether peer or local
3760  *
3761  * Returns 0 on success, non-zero value on failure
3762  */
3763 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3764                         u8 attr_set, u32 mib_val, u8 peer)
3765 {
3766         struct uic_command uic_cmd = {0};
3767         static const char *const action[] = {
3768                 "dme-set",
3769                 "dme-peer-set"
3770         };
3771         const char *set = action[!!peer];
3772         int ret;
3773         int retries = UFS_UIC_COMMAND_RETRIES;
3774
3775         uic_cmd.command = peer ?
3776                 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3777         uic_cmd.argument1 = attr_sel;
3778         uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3779         uic_cmd.argument3 = mib_val;
3780
3781         do {
3782                 /* for peer attributes we retry upon failure */
3783                 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3784                 if (ret)
3785                         dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3786                                 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3787         } while (ret && peer && --retries);
3788
3789         if (ret)
3790                 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3791                         set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3792                         UFS_UIC_COMMAND_RETRIES - retries);
3793
3794         return ret;
3795 }
3796 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3797
3798 /**
3799  * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3800  * @hba: per adapter instance
3801  * @attr_sel: uic command argument1
3802  * @mib_val: the value of the attribute as returned by the UIC command
3803  * @peer: indicate whether peer or local
3804  *
3805  * Returns 0 on success, non-zero value on failure
3806  */
3807 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3808                         u32 *mib_val, u8 peer)
3809 {
3810         struct uic_command uic_cmd = {0};
3811         static const char *const action[] = {
3812                 "dme-get",
3813                 "dme-peer-get"
3814         };
3815         const char *get = action[!!peer];
3816         int ret;
3817         int retries = UFS_UIC_COMMAND_RETRIES;
3818         struct ufs_pa_layer_attr orig_pwr_info;
3819         struct ufs_pa_layer_attr temp_pwr_info;
3820         bool pwr_mode_change = false;
3821
3822         if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3823                 orig_pwr_info = hba->pwr_info;
3824                 temp_pwr_info = orig_pwr_info;
3825
3826                 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3827                     orig_pwr_info.pwr_rx == FAST_MODE) {
3828                         temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3829                         temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3830                         pwr_mode_change = true;
3831                 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3832                     orig_pwr_info.pwr_rx == SLOW_MODE) {
3833                         temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3834                         temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3835                         pwr_mode_change = true;
3836                 }
3837                 if (pwr_mode_change) {
3838                         ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3839                         if (ret)
3840                                 goto out;
3841                 }
3842         }
3843
3844         uic_cmd.command = peer ?
3845                 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3846         uic_cmd.argument1 = attr_sel;
3847
3848         do {
3849                 /* for peer attributes we retry upon failure */
3850                 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3851                 if (ret)
3852                         dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3853                                 get, UIC_GET_ATTR_ID(attr_sel), ret);
3854         } while (ret && peer && --retries);
3855
3856         if (ret)
3857                 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3858                         get, UIC_GET_ATTR_ID(attr_sel),
3859                         UFS_UIC_COMMAND_RETRIES - retries);
3860
3861         if (mib_val && !ret)
3862                 *mib_val = uic_cmd.argument3;
3863
3864         if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3865             && pwr_mode_change)
3866                 ufshcd_change_power_mode(hba, &orig_pwr_info);
3867 out:
3868         return ret;
3869 }
3870 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3871
3872 /**
3873  * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3874  * state) and waits for it to take effect.
3875  *
3876  * @hba: per adapter instance
3877  * @cmd: UIC command to execute
3878  *
3879  * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3880  * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3881  * and device UniPro link and hence it's final completion would be indicated by
3882  * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3883  * addition to normal UIC command completion Status (UCCS). This function only
3884  * returns after the relevant status bits indicate the completion.
3885  *
3886  * Returns 0 on success, non-zero value on failure
3887  */
3888 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3889 {
3890         struct completion uic_async_done;
3891         unsigned long flags;
3892         u8 status;
3893         int ret;
3894         bool reenable_intr = false;
3895
3896         mutex_lock(&hba->uic_cmd_mutex);
3897         init_completion(&uic_async_done);
3898         ufshcd_add_delay_before_dme_cmd(hba);
3899
3900         spin_lock_irqsave(hba->host->host_lock, flags);
3901         if (ufshcd_is_link_broken(hba)) {
3902                 ret = -ENOLINK;
3903                 goto out_unlock;
3904         }
3905         hba->uic_async_done = &uic_async_done;
3906         if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3907                 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3908                 /*
3909                  * Make sure UIC command completion interrupt is disabled before
3910                  * issuing UIC command.
3911                  */
3912                 wmb();
3913                 reenable_intr = true;
3914         }
3915         ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3916         spin_unlock_irqrestore(hba->host->host_lock, flags);
3917         if (ret) {
3918                 dev_err(hba->dev,
3919                         "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3920                         cmd->command, cmd->argument3, ret);
3921                 goto out;
3922         }
3923
3924         if (!wait_for_completion_timeout(hba->uic_async_done,
3925                                          msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3926                 dev_err(hba->dev,
3927                         "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3928                         cmd->command, cmd->argument3);
3929
3930                 if (!cmd->cmd_active) {
3931                         dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
3932                                 __func__);
3933                         goto check_upmcrs;
3934                 }
3935
3936                 ret = -ETIMEDOUT;
3937                 goto out;
3938         }
3939
3940 check_upmcrs:
3941         status = ufshcd_get_upmcrs(hba);
3942         if (status != PWR_LOCAL) {
3943                 dev_err(hba->dev,
3944                         "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3945                         cmd->command, status);
3946                 ret = (status != PWR_OK) ? status : -1;
3947         }
3948 out:
3949         if (ret) {
3950                 ufshcd_print_host_state(hba);
3951                 ufshcd_print_pwr_info(hba);
3952                 ufshcd_print_evt_hist(hba);
3953         }
3954
3955         spin_lock_irqsave(hba->host->host_lock, flags);
3956         hba->active_uic_cmd = NULL;
3957         hba->uic_async_done = NULL;
3958         if (reenable_intr)
3959                 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3960         if (ret) {
3961                 ufshcd_set_link_broken(hba);
3962                 ufshcd_schedule_eh_work(hba);
3963         }
3964 out_unlock:
3965         spin_unlock_irqrestore(hba->host->host_lock, flags);
3966         mutex_unlock(&hba->uic_cmd_mutex);
3967
3968         return ret;
3969 }
3970
3971 /**
3972  * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3973  *                              using DME_SET primitives.
3974  * @hba: per adapter instance
3975  * @mode: powr mode value
3976  *
3977  * Returns 0 on success, non-zero value on failure
3978  */
3979 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3980 {
3981         struct uic_command uic_cmd = {0};
3982         int ret;
3983
3984         if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3985                 ret = ufshcd_dme_set(hba,
3986                                 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3987                 if (ret) {
3988                         dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3989                                                 __func__, ret);
3990                         goto out;
3991                 }
3992         }
3993
3994         uic_cmd.command = UIC_CMD_DME_SET;
3995         uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3996         uic_cmd.argument3 = mode;
3997         ufshcd_hold(hba, false);
3998         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3999         ufshcd_release(hba);
4000
4001 out:
4002         return ret;
4003 }
4004
4005 int ufshcd_link_recovery(struct ufs_hba *hba)
4006 {
4007         int ret;
4008         unsigned long flags;
4009
4010         spin_lock_irqsave(hba->host->host_lock, flags);
4011         hba->ufshcd_state = UFSHCD_STATE_RESET;
4012         ufshcd_set_eh_in_progress(hba);
4013         spin_unlock_irqrestore(hba->host->host_lock, flags);
4014
4015         /* Reset the attached device */
4016         ufshcd_device_reset(hba);
4017
4018         ret = ufshcd_host_reset_and_restore(hba);
4019
4020         spin_lock_irqsave(hba->host->host_lock, flags);
4021         if (ret)
4022                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4023         ufshcd_clear_eh_in_progress(hba);
4024         spin_unlock_irqrestore(hba->host->host_lock, flags);
4025
4026         if (ret)
4027                 dev_err(hba->dev, "%s: link recovery failed, err %d",
4028                         __func__, ret);
4029         else
4030                 ufshcd_clear_ua_wluns(hba);
4031
4032         return ret;
4033 }
4034 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4035
4036 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4037 {
4038         int ret;
4039         struct uic_command uic_cmd = {0};
4040         ktime_t start = ktime_get();
4041
4042         ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4043
4044         uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4045         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4046         trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4047                              ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4048
4049         if (ret)
4050                 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4051                         __func__, ret);
4052         else
4053                 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4054                                                                 POST_CHANGE);
4055
4056         return ret;
4057 }
4058
4059 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4060 {
4061         struct uic_command uic_cmd = {0};
4062         int ret;
4063         ktime_t start = ktime_get();
4064
4065         ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4066
4067         uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4068         ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4069         trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4070                              ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4071
4072         if (ret) {
4073                 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4074                         __func__, ret);
4075         } else {
4076                 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4077                                                                 POST_CHANGE);
4078                 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4079                 hba->ufs_stats.hibern8_exit_cnt++;
4080         }
4081
4082         return ret;
4083 }
4084 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4085
4086 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4087 {
4088         unsigned long flags;
4089         bool update = false;
4090
4091         if (!ufshcd_is_auto_hibern8_supported(hba))
4092                 return;
4093
4094         spin_lock_irqsave(hba->host->host_lock, flags);
4095         if (hba->ahit != ahit) {
4096                 hba->ahit = ahit;
4097                 update = true;
4098         }
4099         spin_unlock_irqrestore(hba->host->host_lock, flags);
4100
4101         if (update && !pm_runtime_suspended(hba->dev)) {
4102                 pm_runtime_get_sync(hba->dev);
4103                 ufshcd_hold(hba, false);
4104                 ufshcd_auto_hibern8_enable(hba);
4105                 ufshcd_release(hba);
4106                 pm_runtime_put(hba->dev);
4107         }
4108 }
4109 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4110
4111 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4112 {
4113         unsigned long flags;
4114
4115         if (!ufshcd_is_auto_hibern8_supported(hba))
4116                 return;
4117
4118         spin_lock_irqsave(hba->host->host_lock, flags);
4119         ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4120         spin_unlock_irqrestore(hba->host->host_lock, flags);
4121 }
4122
4123  /**
4124  * ufshcd_init_pwr_info - setting the POR (power on reset)
4125  * values in hba power info
4126  * @hba: per-adapter instance
4127  */
4128 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4129 {
4130         hba->pwr_info.gear_rx = UFS_PWM_G1;
4131         hba->pwr_info.gear_tx = UFS_PWM_G1;
4132         hba->pwr_info.lane_rx = 1;
4133         hba->pwr_info.lane_tx = 1;
4134         hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4135         hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4136         hba->pwr_info.hs_rate = 0;
4137 }
4138
4139 /**
4140  * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4141  * @hba: per-adapter instance
4142  */
4143 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4144 {
4145         struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4146
4147         if (hba->max_pwr_info.is_valid)
4148                 return 0;
4149
4150         pwr_info->pwr_tx = FAST_MODE;
4151         pwr_info->pwr_rx = FAST_MODE;
4152         pwr_info->hs_rate = PA_HS_MODE_B;
4153
4154         /* Get the connected lane count */
4155         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4156                         &pwr_info->lane_rx);
4157         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4158                         &pwr_info->lane_tx);
4159
4160         if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4161                 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4162                                 __func__,
4163                                 pwr_info->lane_rx,
4164                                 pwr_info->lane_tx);
4165                 return -EINVAL;
4166         }
4167
4168         /*
4169          * First, get the maximum gears of HS speed.
4170          * If a zero value, it means there is no HSGEAR capability.
4171          * Then, get the maximum gears of PWM speed.
4172          */
4173         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4174         if (!pwr_info->gear_rx) {
4175                 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4176                                 &pwr_info->gear_rx);
4177                 if (!pwr_info->gear_rx) {
4178                         dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4179                                 __func__, pwr_info->gear_rx);
4180                         return -EINVAL;
4181                 }
4182                 pwr_info->pwr_rx = SLOW_MODE;
4183         }
4184
4185         ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4186                         &pwr_info->gear_tx);
4187         if (!pwr_info->gear_tx) {
4188                 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4189                                 &pwr_info->gear_tx);
4190                 if (!pwr_info->gear_tx) {
4191                         dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4192                                 __func__, pwr_info->gear_tx);
4193                         return -EINVAL;
4194                 }
4195                 pwr_info->pwr_tx = SLOW_MODE;
4196         }
4197
4198         hba->max_pwr_info.is_valid = true;
4199         return 0;
4200 }
4201
4202 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4203                              struct ufs_pa_layer_attr *pwr_mode)
4204 {
4205         int ret;
4206
4207         /* if already configured to the requested pwr_mode */
4208         if (!hba->force_pmc &&
4209             pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4210             pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4211             pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4212             pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4213             pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4214             pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4215             pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4216                 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4217                 return 0;
4218         }
4219
4220         /*
4221          * Configure attributes for power mode change with below.
4222          * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4223          * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4224          * - PA_HSSERIES
4225          */
4226         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4227         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4228                         pwr_mode->lane_rx);
4229         if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4230                         pwr_mode->pwr_rx == FAST_MODE)
4231                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4232         else
4233                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4234
4235         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4236         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4237                         pwr_mode->lane_tx);
4238         if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4239                         pwr_mode->pwr_tx == FAST_MODE)
4240                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4241         else
4242                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4243
4244         if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4245             pwr_mode->pwr_tx == FASTAUTO_MODE ||
4246             pwr_mode->pwr_rx == FAST_MODE ||
4247             pwr_mode->pwr_tx == FAST_MODE)
4248                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4249                                                 pwr_mode->hs_rate);
4250
4251         if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4252                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4253                                 DL_FC0ProtectionTimeOutVal_Default);
4254                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4255                                 DL_TC0ReplayTimeOutVal_Default);
4256                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4257                                 DL_AFC0ReqTimeOutVal_Default);
4258                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4259                                 DL_FC1ProtectionTimeOutVal_Default);
4260                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4261                                 DL_TC1ReplayTimeOutVal_Default);
4262                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4263                                 DL_AFC1ReqTimeOutVal_Default);
4264
4265                 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4266                                 DL_FC0ProtectionTimeOutVal_Default);
4267                 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4268                                 DL_TC0ReplayTimeOutVal_Default);
4269                 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4270                                 DL_AFC0ReqTimeOutVal_Default);
4271         }
4272
4273         ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4274                         | pwr_mode->pwr_tx);
4275
4276         if (ret) {
4277                 dev_err(hba->dev,
4278                         "%s: power mode change failed %d\n", __func__, ret);
4279         } else {
4280                 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4281                                                                 pwr_mode);
4282
4283                 memcpy(&hba->pwr_info, pwr_mode,
4284                         sizeof(struct ufs_pa_layer_attr));
4285         }
4286
4287         return ret;
4288 }
4289
4290 /**
4291  * ufshcd_config_pwr_mode - configure a new power mode
4292  * @hba: per-adapter instance
4293  * @desired_pwr_mode: desired power configuration
4294  */
4295 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4296                 struct ufs_pa_layer_attr *desired_pwr_mode)
4297 {
4298         struct ufs_pa_layer_attr final_params = { 0 };
4299         int ret;
4300
4301         ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4302                                         desired_pwr_mode, &final_params);
4303
4304         if (ret)
4305                 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4306
4307         ret = ufshcd_change_power_mode(hba, &final_params);
4308
4309         return ret;
4310 }
4311 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4312
4313 /**
4314  * ufshcd_complete_dev_init() - checks device readiness
4315  * @hba: per-adapter instance
4316  *
4317  * Set fDeviceInit flag and poll until device toggles it.
4318  */
4319 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4320 {
4321         int err;
4322         bool flag_res = true;
4323         ktime_t timeout;
4324
4325         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4326                 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4327         if (err) {
4328                 dev_err(hba->dev,
4329                         "%s setting fDeviceInit flag failed with error %d\n",
4330                         __func__, err);
4331                 goto out;
4332         }
4333
4334         /* Poll fDeviceInit flag to be cleared */
4335         timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4336         do {
4337                 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4338                                         QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4339                 if (!flag_res)
4340                         break;
4341                 usleep_range(5000, 10000);
4342         } while (ktime_before(ktime_get(), timeout));
4343
4344         if (err) {
4345                 dev_err(hba->dev,
4346                                 "%s reading fDeviceInit flag failed with error %d\n",
4347                                 __func__, err);
4348         } else if (flag_res) {
4349                 dev_err(hba->dev,
4350                                 "%s fDeviceInit was not cleared by the device\n",
4351                                 __func__);
4352                 err = -EBUSY;
4353         }
4354 out:
4355         return err;
4356 }
4357
4358 /**
4359  * ufshcd_make_hba_operational - Make UFS controller operational
4360  * @hba: per adapter instance
4361  *
4362  * To bring UFS host controller to operational state,
4363  * 1. Enable required interrupts
4364  * 2. Configure interrupt aggregation
4365  * 3. Program UTRL and UTMRL base address
4366  * 4. Configure run-stop-registers
4367  *
4368  * Returns 0 on success, non-zero value on failure
4369  */
4370 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4371 {
4372         int err = 0;
4373         u32 reg;
4374
4375         /* Enable required interrupts */
4376         ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4377
4378         /* Configure interrupt aggregation */
4379         if (ufshcd_is_intr_aggr_allowed(hba))
4380                 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4381         else
4382                 ufshcd_disable_intr_aggr(hba);
4383
4384         /* Configure UTRL and UTMRL base address registers */
4385         ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4386                         REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4387         ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4388                         REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4389         ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4390                         REG_UTP_TASK_REQ_LIST_BASE_L);
4391         ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4392                         REG_UTP_TASK_REQ_LIST_BASE_H);
4393
4394         /*
4395          * Make sure base address and interrupt setup are updated before
4396          * enabling the run/stop registers below.
4397          */
4398         wmb();
4399
4400         /*
4401          * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4402          */
4403         reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4404         if (!(ufshcd_get_lists_status(reg))) {
4405                 ufshcd_enable_run_stop_reg(hba);
4406         } else {
4407                 dev_err(hba->dev,
4408                         "Host controller not ready to process requests");
4409                 err = -EIO;
4410         }
4411
4412         return err;
4413 }
4414 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4415
4416 /**
4417  * ufshcd_hba_stop - Send controller to reset state
4418  * @hba: per adapter instance
4419  */
4420 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4421 {
4422         unsigned long flags;
4423         int err;
4424
4425         /*
4426          * Obtain the host lock to prevent that the controller is disabled
4427          * while the UFS interrupt handler is active on another CPU.
4428          */
4429         spin_lock_irqsave(hba->host->host_lock, flags);
4430         ufshcd_writel(hba, CONTROLLER_DISABLE,  REG_CONTROLLER_ENABLE);
4431         spin_unlock_irqrestore(hba->host->host_lock, flags);
4432
4433         err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4434                                         CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4435                                         10, 1);
4436         if (err)
4437                 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4438 }
4439
4440 /**
4441  * ufshcd_hba_execute_hce - initialize the controller
4442  * @hba: per adapter instance
4443  *
4444  * The controller resets itself and controller firmware initialization
4445  * sequence kicks off. When controller is ready it will set
4446  * the Host Controller Enable bit to 1.
4447  *
4448  * Returns 0 on success, non-zero value on failure
4449  */
4450 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4451 {
4452         int retry_outer = 3;
4453         int retry_inner;
4454
4455 start:
4456         if (!ufshcd_is_hba_active(hba))
4457                 /* change controller state to "reset state" */
4458                 ufshcd_hba_stop(hba);
4459
4460         /* UniPro link is disabled at this point */
4461         ufshcd_set_link_off(hba);
4462
4463         ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4464
4465         /* start controller initialization sequence */
4466         ufshcd_hba_start(hba);
4467
4468         /*
4469          * To initialize a UFS host controller HCE bit must be set to 1.
4470          * During initialization the HCE bit value changes from 1->0->1.
4471          * When the host controller completes initialization sequence
4472          * it sets the value of HCE bit to 1. The same HCE bit is read back
4473          * to check if the controller has completed initialization sequence.
4474          * So without this delay the value HCE = 1, set in the previous
4475          * instruction might be read back.
4476          * This delay can be changed based on the controller.
4477          */
4478         ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4479
4480         /* wait for the host controller to complete initialization */
4481         retry_inner = 50;
4482         while (ufshcd_is_hba_active(hba)) {
4483                 if (retry_inner) {
4484                         retry_inner--;
4485                 } else {
4486                         dev_err(hba->dev,
4487                                 "Controller enable failed\n");
4488                         if (retry_outer) {
4489                                 retry_outer--;
4490                                 goto start;
4491                         }
4492                         return -EIO;
4493                 }
4494                 usleep_range(1000, 1100);
4495         }
4496
4497         /* enable UIC related interrupts */
4498         ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4499
4500         ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4501
4502         return 0;
4503 }
4504
4505 int ufshcd_hba_enable(struct ufs_hba *hba)
4506 {
4507         int ret;
4508
4509         if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4510                 ufshcd_set_link_off(hba);
4511                 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4512
4513                 /* enable UIC related interrupts */
4514                 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4515                 ret = ufshcd_dme_reset(hba);
4516                 if (!ret) {
4517                         ret = ufshcd_dme_enable(hba);
4518                         if (!ret)
4519                                 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4520                         if (ret)
4521                                 dev_err(hba->dev,
4522                                         "Host controller enable failed with non-hce\n");
4523                 }
4524         } else {
4525                 ret = ufshcd_hba_execute_hce(hba);
4526         }
4527
4528         return ret;
4529 }
4530 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4531
4532 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4533 {
4534         int tx_lanes = 0, i, err = 0;
4535
4536         if (!peer)
4537                 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4538                                &tx_lanes);
4539         else
4540                 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4541                                     &tx_lanes);
4542         for (i = 0; i < tx_lanes; i++) {
4543                 if (!peer)
4544                         err = ufshcd_dme_set(hba,
4545                                 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4546                                         UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4547                                         0);
4548                 else
4549                         err = ufshcd_dme_peer_set(hba,
4550                                 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4551                                         UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4552                                         0);
4553                 if (err) {
4554                         dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4555                                 __func__, peer, i, err);
4556                         break;
4557                 }
4558         }
4559
4560         return err;
4561 }
4562
4563 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4564 {
4565         return ufshcd_disable_tx_lcc(hba, true);
4566 }
4567
4568 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4569 {
4570         struct ufs_event_hist *e;
4571
4572         if (id >= UFS_EVT_CNT)
4573                 return;
4574
4575         e = &hba->ufs_stats.event[id];
4576         e->val[e->pos] = val;
4577         e->tstamp[e->pos] = ktime_get();
4578         e->cnt += 1;
4579         e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4580
4581         ufshcd_vops_event_notify(hba, id, &val);
4582 }
4583 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4584
4585 /**
4586  * ufshcd_link_startup - Initialize unipro link startup
4587  * @hba: per adapter instance
4588  *
4589  * Returns 0 for success, non-zero in case of failure
4590  */
4591 static int ufshcd_link_startup(struct ufs_hba *hba)
4592 {
4593         int ret;
4594         int retries = DME_LINKSTARTUP_RETRIES;
4595         bool link_startup_again = false;
4596
4597         /*
4598          * If UFS device isn't active then we will have to issue link startup
4599          * 2 times to make sure the device state move to active.
4600          */
4601         if (!ufshcd_is_ufs_dev_active(hba))
4602                 link_startup_again = true;
4603
4604 link_startup:
4605         do {
4606                 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4607
4608                 ret = ufshcd_dme_link_startup(hba);
4609
4610                 /* check if device is detected by inter-connect layer */
4611                 if (!ret && !ufshcd_is_device_present(hba)) {
4612                         ufshcd_update_evt_hist(hba,
4613                                                UFS_EVT_LINK_STARTUP_FAIL,
4614                                                0);
4615                         dev_err(hba->dev, "%s: Device not present\n", __func__);
4616                         ret = -ENXIO;
4617                         goto out;
4618                 }
4619
4620                 /*
4621                  * DME link lost indication is only received when link is up,
4622                  * but we can't be sure if the link is up until link startup
4623                  * succeeds. So reset the local Uni-Pro and try again.
4624                  */
4625                 if (ret && ufshcd_hba_enable(hba)) {
4626                         ufshcd_update_evt_hist(hba,
4627                                                UFS_EVT_LINK_STARTUP_FAIL,
4628                                                (u32)ret);
4629                         goto out;
4630                 }
4631         } while (ret && retries--);
4632
4633         if (ret) {
4634                 /* failed to get the link up... retire */
4635                 ufshcd_update_evt_hist(hba,
4636                                        UFS_EVT_LINK_STARTUP_FAIL,
4637                                        (u32)ret);
4638                 goto out;
4639         }
4640
4641         if (link_startup_again) {
4642                 link_startup_again = false;
4643                 retries = DME_LINKSTARTUP_RETRIES;
4644                 goto link_startup;
4645         }
4646
4647         /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4648         ufshcd_init_pwr_info(hba);
4649         ufshcd_print_pwr_info(hba);
4650
4651         if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4652                 ret = ufshcd_disable_device_tx_lcc(hba);
4653                 if (ret)
4654                         goto out;
4655         }
4656
4657         /* Include any host controller configuration via UIC commands */
4658         ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4659         if (ret)
4660                 goto out;
4661
4662         /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4663         ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4664         ret = ufshcd_make_hba_operational(hba);
4665 out:
4666         if (ret) {
4667                 dev_err(hba->dev, "link startup failed %d\n", ret);
4668                 ufshcd_print_host_state(hba);
4669                 ufshcd_print_pwr_info(hba);
4670                 ufshcd_print_evt_hist(hba);
4671         }
4672         return ret;
4673 }
4674
4675 /**
4676  * ufshcd_verify_dev_init() - Verify device initialization
4677  * @hba: per-adapter instance
4678  *
4679  * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4680  * device Transport Protocol (UTP) layer is ready after a reset.
4681  * If the UTP layer at the device side is not initialized, it may
4682  * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4683  * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4684  */
4685 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4686 {
4687         int err = 0;
4688         int retries;
4689
4690         ufshcd_hold(hba, false);
4691         mutex_lock(&hba->dev_cmd.lock);
4692         for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4693                 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4694                                                NOP_OUT_TIMEOUT);
4695
4696                 if (!err || err == -ETIMEDOUT)
4697                         break;
4698
4699                 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4700         }
4701         mutex_unlock(&hba->dev_cmd.lock);
4702         ufshcd_release(hba);
4703
4704         if (err)
4705                 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4706         return err;
4707 }
4708
4709 /**
4710  * ufshcd_set_queue_depth - set lun queue depth
4711  * @sdev: pointer to SCSI device
4712  *
4713  * Read bLUQueueDepth value and activate scsi tagged command
4714  * queueing. For WLUN, queue depth is set to 1. For best-effort
4715  * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4716  * value that host can queue.
4717  */
4718 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4719 {
4720         int ret = 0;
4721         u8 lun_qdepth;
4722         struct ufs_hba *hba;
4723
4724         hba = shost_priv(sdev->host);
4725
4726         lun_qdepth = hba->nutrs;
4727         ret = ufshcd_read_unit_desc_param(hba,
4728                                           ufshcd_scsi_to_upiu_lun(sdev->lun),
4729                                           UNIT_DESC_PARAM_LU_Q_DEPTH,
4730                                           &lun_qdepth,
4731                                           sizeof(lun_qdepth));
4732
4733         /* Some WLUN doesn't support unit descriptor */
4734         if (ret == -EOPNOTSUPP)
4735                 lun_qdepth = 1;
4736         else if (!lun_qdepth)
4737                 /* eventually, we can figure out the real queue depth */
4738                 lun_qdepth = hba->nutrs;
4739         else
4740                 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4741
4742         dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4743                         __func__, lun_qdepth);
4744         scsi_change_queue_depth(sdev, lun_qdepth);
4745 }
4746
4747 /*
4748  * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4749  * @hba: per-adapter instance
4750  * @lun: UFS device lun id
4751  * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4752  *
4753  * Returns 0 in case of success and b_lu_write_protect status would be returned
4754  * @b_lu_write_protect parameter.
4755  * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4756  * Returns -EINVAL in case of invalid parameters passed to this function.
4757  */
4758 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4759                             u8 lun,
4760                             u8 *b_lu_write_protect)
4761 {
4762         int ret;
4763
4764         if (!b_lu_write_protect)
4765                 ret = -EINVAL;
4766         /*
4767          * According to UFS device spec, RPMB LU can't be write
4768          * protected so skip reading bLUWriteProtect parameter for
4769          * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4770          */
4771         else if (lun >= hba->dev_info.max_lu_supported)
4772                 ret = -ENOTSUPP;
4773         else
4774                 ret = ufshcd_read_unit_desc_param(hba,
4775                                           lun,
4776                                           UNIT_DESC_PARAM_LU_WR_PROTECT,
4777                                           b_lu_write_protect,
4778                                           sizeof(*b_lu_write_protect));
4779         return ret;
4780 }
4781
4782 /**
4783  * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4784  * status
4785  * @hba: per-adapter instance
4786  * @sdev: pointer to SCSI device
4787  *
4788  */
4789 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4790                                                     struct scsi_device *sdev)
4791 {
4792         if (hba->dev_info.f_power_on_wp_en &&
4793             !hba->dev_info.is_lu_power_on_wp) {
4794                 u8 b_lu_write_protect;
4795
4796                 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4797                                       &b_lu_write_protect) &&
4798                     (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4799                         hba->dev_info.is_lu_power_on_wp = true;
4800         }
4801 }
4802
4803 /**
4804  * ufshcd_slave_alloc - handle initial SCSI device configurations
4805  * @sdev: pointer to SCSI device
4806  *
4807  * Returns success
4808  */
4809 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4810 {
4811         struct ufs_hba *hba;
4812
4813         hba = shost_priv(sdev->host);
4814
4815         /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4816         sdev->use_10_for_ms = 1;
4817
4818         /* DBD field should be set to 1 in mode sense(10) */
4819         sdev->set_dbd_for_ms = 1;
4820
4821         /* allow SCSI layer to restart the device in case of errors */
4822         sdev->allow_restart = 1;
4823
4824         /* REPORT SUPPORTED OPERATION CODES is not supported */
4825         sdev->no_report_opcodes = 1;
4826
4827         /* WRITE_SAME command is not supported */
4828         sdev->no_write_same = 1;
4829
4830         ufshcd_set_queue_depth(sdev);
4831
4832         ufshcd_get_lu_power_on_wp_status(hba, sdev);
4833
4834         return 0;
4835 }
4836
4837 /**
4838  * ufshcd_change_queue_depth - change queue depth
4839  * @sdev: pointer to SCSI device
4840  * @depth: required depth to set
4841  *
4842  * Change queue depth and make sure the max. limits are not crossed.
4843  */
4844 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4845 {
4846         struct ufs_hba *hba = shost_priv(sdev->host);
4847
4848         if (depth > hba->nutrs)
4849                 depth = hba->nutrs;
4850         return scsi_change_queue_depth(sdev, depth);
4851 }
4852
4853 /**
4854  * ufshcd_slave_configure - adjust SCSI device configurations
4855  * @sdev: pointer to SCSI device
4856  */
4857 static int ufshcd_slave_configure(struct scsi_device *sdev)
4858 {
4859         struct ufs_hba *hba = shost_priv(sdev->host);
4860         struct request_queue *q = sdev->request_queue;
4861
4862         blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4863         if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
4864                 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
4865
4866         if (ufshcd_is_rpm_autosuspend_allowed(hba))
4867                 sdev->rpm_autosuspend = 1;
4868
4869         ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4870
4871         return 0;
4872 }
4873
4874 /**
4875  * ufshcd_slave_destroy - remove SCSI device configurations
4876  * @sdev: pointer to SCSI device
4877  */
4878 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4879 {
4880         struct ufs_hba *hba;
4881
4882         hba = shost_priv(sdev->host);
4883         /* Drop the reference as it won't be needed anymore */
4884         if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4885                 unsigned long flags;
4886
4887                 spin_lock_irqsave(hba->host->host_lock, flags);
4888                 hba->sdev_ufs_device = NULL;
4889                 spin_unlock_irqrestore(hba->host->host_lock, flags);
4890         }
4891 }
4892
4893 /**
4894  * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4895  * @lrbp: pointer to local reference block of completed command
4896  * @scsi_status: SCSI command status
4897  *
4898  * Returns value base on SCSI command status
4899  */
4900 static inline int
4901 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4902 {
4903         int result = 0;
4904
4905         switch (scsi_status) {
4906         case SAM_STAT_CHECK_CONDITION:
4907                 ufshcd_copy_sense_data(lrbp);
4908                 fallthrough;
4909         case SAM_STAT_GOOD:
4910                 result |= DID_OK << 16 | scsi_status;
4911                 break;
4912         case SAM_STAT_TASK_SET_FULL:
4913         case SAM_STAT_BUSY:
4914         case SAM_STAT_TASK_ABORTED:
4915                 ufshcd_copy_sense_data(lrbp);
4916                 result |= scsi_status;
4917                 break;
4918         default:
4919                 result |= DID_ERROR << 16;
4920                 break;
4921         } /* end of switch */
4922
4923         return result;
4924 }
4925
4926 /**
4927  * ufshcd_transfer_rsp_status - Get overall status of the response
4928  * @hba: per adapter instance
4929  * @lrbp: pointer to local reference block of completed command
4930  *
4931  * Returns result of the command to notify SCSI midlayer
4932  */
4933 static inline int
4934 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4935 {
4936         int result = 0;
4937         int scsi_status;
4938         int ocs;
4939
4940         /* overall command status of utrd */
4941         ocs = ufshcd_get_tr_ocs(lrbp);
4942
4943         if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4944                 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4945                                         MASK_RSP_UPIU_RESULT)
4946                         ocs = OCS_SUCCESS;
4947         }
4948
4949         switch (ocs) {
4950         case OCS_SUCCESS:
4951                 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4952                 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4953                 switch (result) {
4954                 case UPIU_TRANSACTION_RESPONSE:
4955                         /*
4956                          * get the response UPIU result to extract
4957                          * the SCSI command status
4958                          */
4959                         result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4960
4961                         /*
4962                          * get the result based on SCSI status response
4963                          * to notify the SCSI midlayer of the command status
4964                          */
4965                         scsi_status = result & MASK_SCSI_STATUS;
4966                         result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4967
4968                         /*
4969                          * Currently we are only supporting BKOPs exception
4970                          * events hence we can ignore BKOPs exception event
4971                          * during power management callbacks. BKOPs exception
4972                          * event is not expected to be raised in runtime suspend
4973                          * callback as it allows the urgent bkops.
4974                          * During system suspend, we are anyway forcefully
4975                          * disabling the bkops and if urgent bkops is needed
4976                          * it will be enabled on system resume. Long term
4977                          * solution could be to abort the system suspend if
4978                          * UFS device needs urgent BKOPs.
4979                          */
4980                         if (!hba->pm_op_in_progress &&
4981                             !ufshcd_eh_in_progress(hba) &&
4982                             ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4983                             schedule_work(&hba->eeh_work)) {
4984                                 /*
4985                                  * Prevent suspend once eeh_work is scheduled
4986                                  * to avoid deadlock between ufshcd_suspend
4987                                  * and exception event handler.
4988                                  */
4989                                 pm_runtime_get_noresume(hba->dev);
4990                         }
4991                         break;
4992                 case UPIU_TRANSACTION_REJECT_UPIU:
4993                         /* TODO: handle Reject UPIU Response */
4994                         result = DID_ERROR << 16;
4995                         dev_err(hba->dev,
4996                                 "Reject UPIU not fully implemented\n");
4997                         break;
4998                 default:
4999                         dev_err(hba->dev,
5000                                 "Unexpected request response code = %x\n",
5001                                 result);
5002                         result = DID_ERROR << 16;
5003                         break;
5004                 }
5005                 break;
5006         case OCS_ABORTED:
5007                 result |= DID_ABORT << 16;
5008                 break;
5009         case OCS_INVALID_COMMAND_STATUS:
5010                 result |= DID_REQUEUE << 16;
5011                 break;
5012         case OCS_INVALID_CMD_TABLE_ATTR:
5013         case OCS_INVALID_PRDT_ATTR:
5014         case OCS_MISMATCH_DATA_BUF_SIZE:
5015         case OCS_MISMATCH_RESP_UPIU_SIZE:
5016         case OCS_PEER_COMM_FAILURE:
5017         case OCS_FATAL_ERROR:
5018         case OCS_DEVICE_FATAL_ERROR:
5019         case OCS_INVALID_CRYPTO_CONFIG:
5020         case OCS_GENERAL_CRYPTO_ERROR:
5021         default:
5022                 result |= DID_ERROR << 16;
5023                 dev_err(hba->dev,
5024                                 "OCS error from controller = %x for tag %d\n",
5025                                 ocs, lrbp->task_tag);
5026                 ufshcd_print_evt_hist(hba);
5027                 ufshcd_print_host_state(hba);
5028                 break;
5029         } /* end of switch */
5030
5031         if ((host_byte(result) != DID_OK) &&
5032             (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5033                 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5034         return result;
5035 }
5036
5037 /**
5038  * ufshcd_uic_cmd_compl - handle completion of uic command
5039  * @hba: per adapter instance
5040  * @intr_status: interrupt status generated by the controller
5041  *
5042  * Returns
5043  *  IRQ_HANDLED - If interrupt is valid
5044  *  IRQ_NONE    - If invalid interrupt
5045  */
5046 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5047 {
5048         irqreturn_t retval = IRQ_NONE;
5049
5050         if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5051                 hba->active_uic_cmd->argument2 |=
5052                         ufshcd_get_uic_cmd_result(hba);
5053                 hba->active_uic_cmd->argument3 =
5054                         ufshcd_get_dme_attr_val(hba);
5055                 if (!hba->uic_async_done)
5056                         hba->active_uic_cmd->cmd_active = 0;
5057                 complete(&hba->active_uic_cmd->done);
5058                 retval = IRQ_HANDLED;
5059         }
5060
5061         if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5062                 hba->active_uic_cmd->cmd_active = 0;
5063                 complete(hba->uic_async_done);
5064                 retval = IRQ_HANDLED;
5065         }
5066
5067         if (retval == IRQ_HANDLED)
5068                 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5069                                              UFS_CMD_COMP);
5070         return retval;
5071 }
5072
5073 /**
5074  * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5075  * @hba: per adapter instance
5076  * @completed_reqs: requests to complete
5077  */
5078 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5079                                         unsigned long completed_reqs)
5080 {
5081         struct ufshcd_lrb *lrbp;
5082         struct scsi_cmnd *cmd;
5083         int result;
5084         int index;
5085         bool update_scaling = false;
5086
5087         for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5088                 lrbp = &hba->lrb[index];
5089                 lrbp->in_use = false;
5090                 lrbp->compl_time_stamp = ktime_get();
5091                 cmd = lrbp->cmd;
5092                 if (cmd) {
5093                         ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5094                         result = ufshcd_transfer_rsp_status(hba, lrbp);
5095                         scsi_dma_unmap(cmd);
5096                         cmd->result = result;
5097                         /* Mark completed command as NULL in LRB */
5098                         lrbp->cmd = NULL;
5099                         /* Do not touch lrbp after scsi done */
5100                         cmd->scsi_done(cmd);
5101                         __ufshcd_release(hba);
5102                         update_scaling = true;
5103                 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5104                         lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5105                         if (hba->dev_cmd.complete) {
5106                                 ufshcd_add_command_trace(hba, index,
5107                                                          UFS_DEV_COMP);
5108                                 complete(hba->dev_cmd.complete);
5109                                 update_scaling = true;
5110                         }
5111                 }
5112                 if (ufshcd_is_clkscaling_supported(hba) && update_scaling)
5113                         hba->clk_scaling.active_reqs--;
5114         }
5115
5116         /* clear corresponding bits of completed commands */
5117         hba->outstanding_reqs ^= completed_reqs;
5118
5119         ufshcd_clk_scaling_update_busy(hba);
5120 }
5121
5122 /**
5123  * ufshcd_transfer_req_compl - handle SCSI and query command completion
5124  * @hba: per adapter instance
5125  *
5126  * Returns
5127  *  IRQ_HANDLED - If interrupt is valid
5128  *  IRQ_NONE    - If invalid interrupt
5129  */
5130 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5131 {
5132         unsigned long completed_reqs;
5133         u32 tr_doorbell;
5134
5135         /* Resetting interrupt aggregation counters first and reading the
5136          * DOOR_BELL afterward allows us to handle all the completed requests.
5137          * In order to prevent other interrupts starvation the DB is read once
5138          * after reset. The down side of this solution is the possibility of
5139          * false interrupt if device completes another request after resetting
5140          * aggregation and before reading the DB.
5141          */
5142         if (ufshcd_is_intr_aggr_allowed(hba) &&
5143             !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5144                 ufshcd_reset_intr_aggr(hba);
5145
5146         tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5147         completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5148
5149         if (completed_reqs) {
5150                 __ufshcd_transfer_req_compl(hba, completed_reqs);
5151                 return IRQ_HANDLED;
5152         } else {
5153                 return IRQ_NONE;
5154         }
5155 }
5156
5157 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5158 {
5159         return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5160                                        QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5161                                        &ee_ctrl_mask);
5162 }
5163
5164 int ufshcd_write_ee_control(struct ufs_hba *hba)
5165 {
5166         int err;
5167
5168         mutex_lock(&hba->ee_ctrl_mutex);
5169         err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5170         mutex_unlock(&hba->ee_ctrl_mutex);
5171         if (err)
5172                 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5173                         __func__, err);
5174         return err;
5175 }
5176
5177 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5178                              u16 set, u16 clr)
5179 {
5180         u16 new_mask, ee_ctrl_mask;
5181         int err = 0;
5182
5183         mutex_lock(&hba->ee_ctrl_mutex);
5184         new_mask = (*mask & ~clr) | set;
5185         ee_ctrl_mask = new_mask | *other_mask;
5186         if (ee_ctrl_mask != hba->ee_ctrl_mask)
5187                 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5188         /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5189         if (!err) {
5190                 hba->ee_ctrl_mask = ee_ctrl_mask;
5191                 *mask = new_mask;
5192         }
5193         mutex_unlock(&hba->ee_ctrl_mutex);
5194         return err;
5195 }
5196
5197 /**
5198  * ufshcd_disable_ee - disable exception event
5199  * @hba: per-adapter instance
5200  * @mask: exception event to disable
5201  *
5202  * Disables exception event in the device so that the EVENT_ALERT
5203  * bit is not set.
5204  *
5205  * Returns zero on success, non-zero error value on failure.
5206  */
5207 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5208 {
5209         return ufshcd_update_ee_drv_mask(hba, 0, mask);
5210 }
5211
5212 /**
5213  * ufshcd_enable_ee - enable exception event
5214  * @hba: per-adapter instance
5215  * @mask: exception event to enable
5216  *
5217  * Enable corresponding exception event in the device to allow
5218  * device to alert host in critical scenarios.
5219  *
5220  * Returns zero on success, non-zero error value on failure.
5221  */
5222 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5223 {
5224         return ufshcd_update_ee_drv_mask(hba, mask, 0);
5225 }
5226
5227 /**
5228  * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5229  * @hba: per-adapter instance
5230  *
5231  * Allow device to manage background operations on its own. Enabling
5232  * this might lead to inconsistent latencies during normal data transfers
5233  * as the device is allowed to manage its own way of handling background
5234  * operations.
5235  *
5236  * Returns zero on success, non-zero on failure.
5237  */
5238 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5239 {
5240         int err = 0;
5241
5242         if (hba->auto_bkops_enabled)
5243                 goto out;
5244
5245         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5246                         QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5247         if (err) {
5248                 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5249                                 __func__, err);
5250                 goto out;
5251         }
5252
5253         hba->auto_bkops_enabled = true;
5254         trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5255
5256         /* No need of URGENT_BKOPS exception from the device */
5257         err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5258         if (err)
5259                 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5260                                 __func__, err);
5261 out:
5262         return err;
5263 }
5264
5265 /**
5266  * ufshcd_disable_auto_bkops - block device in doing background operations
5267  * @hba: per-adapter instance
5268  *
5269  * Disabling background operations improves command response latency but
5270  * has drawback of device moving into critical state where the device is
5271  * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5272  * host is idle so that BKOPS are managed effectively without any negative
5273  * impacts.
5274  *
5275  * Returns zero on success, non-zero on failure.
5276  */
5277 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5278 {
5279         int err = 0;
5280
5281         if (!hba->auto_bkops_enabled)
5282                 goto out;
5283
5284         /*
5285          * If host assisted BKOPs is to be enabled, make sure
5286          * urgent bkops exception is allowed.
5287          */
5288         err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5289         if (err) {
5290                 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5291                                 __func__, err);
5292                 goto out;
5293         }
5294
5295         err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5296                         QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5297         if (err) {
5298                 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5299                                 __func__, err);
5300                 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5301                 goto out;
5302         }
5303
5304         hba->auto_bkops_enabled = false;
5305         trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5306         hba->is_urgent_bkops_lvl_checked = false;
5307 out:
5308         return err;
5309 }
5310
5311 /**
5312  * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5313  * @hba: per adapter instance
5314  *
5315  * After a device reset the device may toggle the BKOPS_EN flag
5316  * to default value. The s/w tracking variables should be updated
5317  * as well. This function would change the auto-bkops state based on
5318  * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5319  */
5320 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5321 {
5322         if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5323                 hba->auto_bkops_enabled = false;
5324                 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5325                 ufshcd_enable_auto_bkops(hba);
5326         } else {
5327                 hba->auto_bkops_enabled = true;
5328                 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5329                 ufshcd_disable_auto_bkops(hba);
5330         }
5331         hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5332         hba->is_urgent_bkops_lvl_checked = false;
5333 }
5334
5335 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5336 {
5337         return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5338                         QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5339 }
5340
5341 /**
5342  * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5343  * @hba: per-adapter instance
5344  * @status: bkops_status value
5345  *
5346  * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5347  * flag in the device to permit background operations if the device
5348  * bkops_status is greater than or equal to "status" argument passed to
5349  * this function, disable otherwise.
5350  *
5351  * Returns 0 for success, non-zero in case of failure.
5352  *
5353  * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5354  * to know whether auto bkops is enabled or disabled after this function
5355  * returns control to it.
5356  */
5357 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5358                              enum bkops_status status)
5359 {
5360         int err;
5361         u32 curr_status = 0;
5362
5363         err = ufshcd_get_bkops_status(hba, &curr_status);
5364         if (err) {
5365                 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5366                                 __func__, err);
5367                 goto out;
5368         } else if (curr_status > BKOPS_STATUS_MAX) {
5369                 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5370                                 __func__, curr_status);
5371                 err = -EINVAL;
5372                 goto out;
5373         }
5374
5375         if (curr_status >= status)
5376                 err = ufshcd_enable_auto_bkops(hba);
5377         else
5378                 err = ufshcd_disable_auto_bkops(hba);
5379 out:
5380         return err;
5381 }
5382
5383 /**
5384  * ufshcd_urgent_bkops - handle urgent bkops exception event
5385  * @hba: per-adapter instance
5386  *
5387  * Enable fBackgroundOpsEn flag in the device to permit background
5388  * operations.
5389  *
5390  * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5391  * and negative error value for any other failure.
5392  */
5393 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5394 {
5395         return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5396 }
5397
5398 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5399 {
5400         return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5401                         QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5402 }
5403
5404 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5405 {
5406         int err;
5407         u32 curr_status = 0;
5408
5409         if (hba->is_urgent_bkops_lvl_checked)
5410                 goto enable_auto_bkops;
5411
5412         err = ufshcd_get_bkops_status(hba, &curr_status);
5413         if (err) {
5414                 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5415                                 __func__, err);
5416                 goto out;
5417         }
5418
5419         /*
5420          * We are seeing that some devices are raising the urgent bkops
5421          * exception events even when BKOPS status doesn't indicate performace
5422          * impacted or critical. Handle these device by determining their urgent
5423          * bkops status at runtime.
5424          */
5425         if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5426                 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5427                                 __func__, curr_status);
5428                 /* update the current status as the urgent bkops level */
5429                 hba->urgent_bkops_lvl = curr_status;
5430                 hba->is_urgent_bkops_lvl_checked = true;
5431         }
5432
5433 enable_auto_bkops:
5434         err = ufshcd_enable_auto_bkops(hba);
5435 out:
5436         if (err < 0)
5437                 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5438                                 __func__, err);
5439 }
5440
5441 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5442 {
5443         u8 index;
5444         enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5445                                    UPIU_QUERY_OPCODE_CLEAR_FLAG;
5446
5447         index = ufshcd_wb_get_query_index(hba);
5448         return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5449 }
5450
5451 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5452 {
5453         int ret;
5454
5455         if (!ufshcd_is_wb_allowed(hba))
5456                 return 0;
5457
5458         if (!(enable ^ hba->dev_info.wb_enabled))
5459                 return 0;
5460
5461         ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5462         if (ret) {
5463                 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5464                         __func__, enable ? "enable" : "disable", ret);
5465                 return ret;
5466         }
5467
5468         hba->dev_info.wb_enabled = enable;
5469         dev_info(hba->dev, "%s Write Booster %s\n",
5470                         __func__, enable ? "enabled" : "disabled");
5471
5472         return ret;
5473 }
5474
5475 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5476 {
5477         int ret;
5478
5479         ret = __ufshcd_wb_toggle(hba, set,
5480                         QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5481         if (ret) {
5482                 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5483                         __func__, set ? "enable" : "disable", ret);
5484                 return;
5485         }
5486         dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5487                         __func__, set ? "enabled" : "disabled");
5488 }
5489
5490 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5491 {
5492         int ret;
5493
5494         if (!ufshcd_is_wb_allowed(hba) ||
5495             hba->dev_info.wb_buf_flush_enabled == enable)
5496                 return;
5497
5498         ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5499         if (ret) {
5500                 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5501                         enable ? "enable" : "disable", ret);
5502                 return;
5503         }
5504
5505         hba->dev_info.wb_buf_flush_enabled = enable;
5506
5507         dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5508                         __func__, enable ? "enabled" : "disabled");
5509 }
5510
5511 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5512                                                 u32 avail_buf)
5513 {
5514         u32 cur_buf;
5515         int ret;
5516         u8 index;
5517
5518         index = ufshcd_wb_get_query_index(hba);
5519         ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5520                                               QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5521                                               index, 0, &cur_buf);
5522         if (ret) {
5523                 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5524                         __func__, ret);
5525                 return false;
5526         }
5527
5528         if (!cur_buf) {
5529                 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5530                          cur_buf);
5531                 return false;
5532         }
5533         /* Let it continue to flush when available buffer exceeds threshold */
5534         if (avail_buf < hba->vps->wb_flush_threshold)
5535                 return true;
5536
5537         return false;
5538 }
5539
5540 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5541 {
5542         int ret;
5543         u32 avail_buf;
5544         u8 index;
5545
5546         if (!ufshcd_is_wb_allowed(hba))
5547                 return false;
5548         /*
5549          * The ufs device needs the vcc to be ON to flush.
5550          * With user-space reduction enabled, it's enough to enable flush
5551          * by checking only the available buffer. The threshold
5552          * defined here is > 90% full.
5553          * With user-space preserved enabled, the current-buffer
5554          * should be checked too because the wb buffer size can reduce
5555          * when disk tends to be full. This info is provided by current
5556          * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5557          * keeping vcc on when current buffer is empty.
5558          */
5559         index = ufshcd_wb_get_query_index(hba);
5560         ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5561                                       QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5562                                       index, 0, &avail_buf);
5563         if (ret) {
5564                 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5565                          __func__, ret);
5566                 return false;
5567         }
5568
5569         if (!hba->dev_info.b_presrv_uspc_en) {
5570                 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5571                         return true;
5572                 return false;
5573         }
5574
5575         return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5576 }
5577
5578 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5579 {
5580         struct ufs_hba *hba = container_of(to_delayed_work(work),
5581                                            struct ufs_hba,
5582                                            rpm_dev_flush_recheck_work);
5583         /*
5584          * To prevent unnecessary VCC power drain after device finishes
5585          * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5586          * after a certain delay to recheck the threshold by next runtime
5587          * suspend.
5588          */
5589         pm_runtime_get_sync(hba->dev);
5590         pm_runtime_put_sync(hba->dev);
5591 }
5592
5593 /**
5594  * ufshcd_exception_event_handler - handle exceptions raised by device
5595  * @work: pointer to work data
5596  *
5597  * Read bExceptionEventStatus attribute from the device and handle the
5598  * exception event accordingly.
5599  */
5600 static void ufshcd_exception_event_handler(struct work_struct *work)
5601 {
5602         struct ufs_hba *hba;
5603         int err;
5604         u32 status = 0;
5605         hba = container_of(work, struct ufs_hba, eeh_work);
5606
5607         pm_runtime_get_sync(hba->dev);
5608         ufshcd_scsi_block_requests(hba);
5609         err = ufshcd_get_ee_status(hba, &status);
5610         if (err) {
5611                 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5612                                 __func__, err);
5613                 goto out;
5614         }
5615
5616         trace_ufshcd_exception_event(dev_name(hba->dev), status);
5617
5618         if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5619                 ufshcd_bkops_exception_event_handler(hba);
5620
5621         ufs_debugfs_exception_event(hba, status);
5622 out:
5623         ufshcd_scsi_unblock_requests(hba);
5624         /*
5625          * pm_runtime_get_noresume is called while scheduling
5626          * eeh_work to avoid suspend racing with exception work.
5627          * Hence decrement usage counter using pm_runtime_put_noidle
5628          * to allow suspend on completion of exception event handler.
5629          */
5630         pm_runtime_put_noidle(hba->dev);
5631         pm_runtime_put(hba->dev);
5632         return;
5633 }
5634
5635 /* Complete requests that have door-bell cleared */
5636 static void ufshcd_complete_requests(struct ufs_hba *hba)
5637 {
5638         ufshcd_transfer_req_compl(hba);
5639         ufshcd_tmc_handler(hba);
5640 }
5641
5642 /**
5643  * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5644  *                              to recover from the DL NAC errors or not.
5645  * @hba: per-adapter instance
5646  *
5647  * Returns true if error handling is required, false otherwise
5648  */
5649 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5650 {
5651         unsigned long flags;
5652         bool err_handling = true;
5653
5654         spin_lock_irqsave(hba->host->host_lock, flags);
5655         /*
5656          * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5657          * device fatal error and/or DL NAC & REPLAY timeout errors.
5658          */
5659         if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5660                 goto out;
5661
5662         if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5663             ((hba->saved_err & UIC_ERROR) &&
5664              (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5665                 goto out;
5666
5667         if ((hba->saved_err & UIC_ERROR) &&
5668             (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5669                 int err;
5670                 /*
5671                  * wait for 50ms to see if we can get any other errors or not.
5672                  */
5673                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5674                 msleep(50);
5675                 spin_lock_irqsave(hba->host->host_lock, flags);
5676
5677                 /*
5678                  * now check if we have got any other severe errors other than
5679                  * DL NAC error?
5680                  */
5681                 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5682                     ((hba->saved_err & UIC_ERROR) &&
5683                     (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5684                         goto out;
5685
5686                 /*
5687                  * As DL NAC is the only error received so far, send out NOP
5688                  * command to confirm if link is still active or not.
5689                  *   - If we don't get any response then do error recovery.
5690                  *   - If we get response then clear the DL NAC error bit.
5691                  */
5692
5693                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5694                 err = ufshcd_verify_dev_init(hba);
5695                 spin_lock_irqsave(hba->host->host_lock, flags);
5696
5697                 if (err)
5698                         goto out;
5699
5700                 /* Link seems to be alive hence ignore the DL NAC errors */
5701                 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5702                         hba->saved_err &= ~UIC_ERROR;
5703                 /* clear NAC error */
5704                 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5705                 if (!hba->saved_uic_err)
5706                         err_handling = false;
5707         }
5708 out:
5709         spin_unlock_irqrestore(hba->host->host_lock, flags);
5710         return err_handling;
5711 }
5712
5713 /* host lock must be held before calling this func */
5714 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5715 {
5716         return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5717                (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5718 }
5719
5720 /* host lock must be held before calling this func */
5721 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5722 {
5723         /* handle fatal errors only when link is not in error state */
5724         if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5725                 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5726                     ufshcd_is_saved_err_fatal(hba))
5727                         hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5728                 else
5729                         hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5730                 queue_work(hba->eh_wq, &hba->eh_work);
5731         }
5732 }
5733
5734 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5735 {
5736         down_write(&hba->clk_scaling_lock);
5737         hba->clk_scaling.is_allowed = allow;
5738         up_write(&hba->clk_scaling_lock);
5739 }
5740
5741 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5742 {
5743         if (suspend) {
5744                 if (hba->clk_scaling.is_enabled)
5745                         ufshcd_suspend_clkscaling(hba);
5746                 ufshcd_clk_scaling_allow(hba, false);
5747         } else {
5748                 ufshcd_clk_scaling_allow(hba, true);
5749                 if (hba->clk_scaling.is_enabled)
5750                         ufshcd_resume_clkscaling(hba);
5751         }
5752 }
5753
5754 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5755 {
5756         pm_runtime_get_sync(hba->dev);
5757         if (pm_runtime_status_suspended(hba->dev) || hba->is_sys_suspended) {
5758                 enum ufs_pm_op pm_op;
5759
5760                 /*
5761                  * Don't assume anything of pm_runtime_get_sync(), if
5762                  * resume fails, irq and clocks can be OFF, and powers
5763                  * can be OFF or in LPM.
5764                  */
5765                 ufshcd_setup_hba_vreg(hba, true);
5766                 ufshcd_enable_irq(hba);
5767                 ufshcd_setup_vreg(hba, true);
5768                 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5769                 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5770                 ufshcd_hold(hba, false);
5771                 if (!ufshcd_is_clkgating_allowed(hba))
5772                         ufshcd_setup_clocks(hba, true);
5773                 ufshcd_release(hba);
5774                 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5775                 ufshcd_vops_resume(hba, pm_op);
5776         } else {
5777                 ufshcd_hold(hba, false);
5778                 if (ufshcd_is_clkscaling_supported(hba) &&
5779                     hba->clk_scaling.is_enabled)
5780                         ufshcd_suspend_clkscaling(hba);
5781                 ufshcd_clk_scaling_allow(hba, false);
5782         }
5783         ufshcd_scsi_block_requests(hba);
5784         /* Drain ufshcd_queuecommand() */
5785         down_write(&hba->clk_scaling_lock);
5786         up_write(&hba->clk_scaling_lock);
5787         cancel_work_sync(&hba->eeh_work);
5788 }
5789
5790 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5791 {
5792         ufshcd_scsi_unblock_requests(hba);
5793         ufshcd_release(hba);
5794         if (ufshcd_is_clkscaling_supported(hba))
5795                 ufshcd_clk_scaling_suspend(hba, false);
5796         ufshcd_clear_ua_wluns(hba);
5797         pm_runtime_put(hba->dev);
5798 }
5799
5800 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5801 {
5802         return (!hba->is_powered || hba->shutting_down ||
5803                 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5804                 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5805                    ufshcd_is_link_broken(hba))));
5806 }
5807
5808 #ifdef CONFIG_PM
5809 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5810 {
5811         struct Scsi_Host *shost = hba->host;
5812         struct scsi_device *sdev;
5813         struct request_queue *q;
5814         int ret;
5815
5816         hba->is_sys_suspended = false;
5817         /*
5818          * Set RPM status of hba device to RPM_ACTIVE,
5819          * this also clears its runtime error.
5820          */
5821         ret = pm_runtime_set_active(hba->dev);
5822         /*
5823          * If hba device had runtime error, we also need to resume those
5824          * scsi devices under hba in case any of them has failed to be
5825          * resumed due to hba runtime resume failure. This is to unblock
5826          * blk_queue_enter in case there are bios waiting inside it.
5827          */
5828         if (!ret) {
5829                 shost_for_each_device(sdev, shost) {
5830                         q = sdev->request_queue;
5831                         if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5832                                        q->rpm_status == RPM_SUSPENDING))
5833                                 pm_request_resume(q->dev);
5834                 }
5835         }
5836 }
5837 #else
5838 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
5839 {
5840 }
5841 #endif
5842
5843 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
5844 {
5845         struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
5846         u32 mode;
5847
5848         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
5849
5850         if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
5851                 return true;
5852
5853         if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
5854                 return true;
5855
5856         return false;
5857 }
5858
5859 /**
5860  * ufshcd_err_handler - handle UFS errors that require s/w attention
5861  * @work: pointer to work structure
5862  */
5863 static void ufshcd_err_handler(struct work_struct *work)
5864 {
5865         struct ufs_hba *hba;
5866         unsigned long flags;
5867         bool err_xfer = false;
5868         bool err_tm = false;
5869         int err = 0, pmc_err;
5870         int tag;
5871         bool needs_reset = false, needs_restore = false;
5872
5873         hba = container_of(work, struct ufs_hba, eh_work);
5874
5875         down(&hba->host_sem);
5876         spin_lock_irqsave(hba->host->host_lock, flags);
5877         if (ufshcd_err_handling_should_stop(hba)) {
5878                 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5879                         hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5880                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5881                 up(&hba->host_sem);
5882                 return;
5883         }
5884         ufshcd_set_eh_in_progress(hba);
5885         spin_unlock_irqrestore(hba->host->host_lock, flags);
5886         ufshcd_err_handling_prepare(hba);
5887         spin_lock_irqsave(hba->host->host_lock, flags);
5888         if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5889                 hba->ufshcd_state = UFSHCD_STATE_RESET;
5890
5891         /* Complete requests that have door-bell cleared by h/w */
5892         ufshcd_complete_requests(hba);
5893
5894         /*
5895          * A full reset and restore might have happened after preparation
5896          * is finished, double check whether we should stop.
5897          */
5898         if (ufshcd_err_handling_should_stop(hba))
5899                 goto skip_err_handling;
5900
5901         if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5902                 bool ret;
5903
5904                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5905                 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5906                 ret = ufshcd_quirk_dl_nac_errors(hba);
5907                 spin_lock_irqsave(hba->host->host_lock, flags);
5908                 if (!ret && ufshcd_err_handling_should_stop(hba))
5909                         goto skip_err_handling;
5910         }
5911
5912         if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
5913             (hba->saved_uic_err &&
5914              (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
5915                 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
5916
5917                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5918                 ufshcd_print_host_state(hba);
5919                 ufshcd_print_pwr_info(hba);
5920                 ufshcd_print_evt_hist(hba);
5921                 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5922                 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
5923                 spin_lock_irqsave(hba->host->host_lock, flags);
5924         }
5925
5926         /*
5927          * if host reset is required then skip clearing the pending
5928          * transfers forcefully because they will get cleared during
5929          * host reset and restore
5930          */
5931         if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5932             ufshcd_is_saved_err_fatal(hba) ||
5933             ((hba->saved_err & UIC_ERROR) &&
5934              (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5935                                     UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
5936                 needs_reset = true;
5937                 goto do_reset;
5938         }
5939
5940         /*
5941          * If LINERESET was caught, UFS might have been put to PWM mode,
5942          * check if power mode restore is needed.
5943          */
5944         if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
5945                 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5946                 if (!hba->saved_uic_err)
5947                         hba->saved_err &= ~UIC_ERROR;
5948                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5949                 if (ufshcd_is_pwr_mode_restore_needed(hba))
5950                         needs_restore = true;
5951                 spin_lock_irqsave(hba->host->host_lock, flags);
5952                 if (!hba->saved_err && !needs_restore)
5953                         goto skip_err_handling;
5954         }
5955
5956         hba->silence_err_logs = true;
5957         /* release lock as clear command might sleep */
5958         spin_unlock_irqrestore(hba->host->host_lock, flags);
5959         /* Clear pending transfer requests */
5960         for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5961                 if (ufshcd_try_to_abort_task(hba, tag)) {
5962                         err_xfer = true;
5963                         goto lock_skip_pending_xfer_clear;
5964                 }
5965         }
5966
5967         /* Clear pending task management requests */
5968         for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5969                 if (ufshcd_clear_tm_cmd(hba, tag)) {
5970                         err_tm = true;
5971                         goto lock_skip_pending_xfer_clear;
5972                 }
5973         }
5974
5975 lock_skip_pending_xfer_clear:
5976         spin_lock_irqsave(hba->host->host_lock, flags);
5977
5978         /* Complete the requests that are cleared by s/w */
5979         ufshcd_complete_requests(hba);
5980         hba->silence_err_logs = false;
5981
5982         if (err_xfer || err_tm) {
5983                 needs_reset = true;
5984                 goto do_reset;
5985         }
5986
5987         /*
5988          * After all reqs and tasks are cleared from doorbell,
5989          * now it is safe to retore power mode.
5990          */
5991         if (needs_restore) {
5992                 spin_unlock_irqrestore(hba->host->host_lock, flags);
5993                 /*
5994                  * Hold the scaling lock just in case dev cmds
5995                  * are sent via bsg and/or sysfs.
5996                  */
5997                 down_write(&hba->clk_scaling_lock);
5998                 hba->force_pmc = true;
5999                 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6000                 if (pmc_err) {
6001                         needs_reset = true;
6002                         dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6003                                         __func__, pmc_err);
6004                 }
6005                 hba->force_pmc = false;
6006                 ufshcd_print_pwr_info(hba);
6007                 up_write(&hba->clk_scaling_lock);
6008                 spin_lock_irqsave(hba->host->host_lock, flags);
6009         }
6010
6011 do_reset:
6012         /* Fatal errors need reset */
6013         if (needs_reset) {
6014                 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
6015
6016                 /*
6017                  * ufshcd_reset_and_restore() does the link reinitialization
6018                  * which will need atleast one empty doorbell slot to send the
6019                  * device management commands (NOP and query commands).
6020                  * If there is no slot empty at this moment then free up last
6021                  * slot forcefully.
6022                  */
6023                 if (hba->outstanding_reqs == max_doorbells)
6024                         __ufshcd_transfer_req_compl(hba,
6025                                                     (1UL << (hba->nutrs - 1)));
6026
6027                 hba->force_reset = false;
6028                 spin_unlock_irqrestore(hba->host->host_lock, flags);
6029                 err = ufshcd_reset_and_restore(hba);
6030                 if (err)
6031                         dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6032                                         __func__, err);
6033                 else
6034                         ufshcd_recover_pm_error(hba);
6035                 spin_lock_irqsave(hba->host->host_lock, flags);
6036         }
6037
6038 skip_err_handling:
6039         if (!needs_reset) {
6040                 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6041                         hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6042                 if (hba->saved_err || hba->saved_uic_err)
6043                         dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6044                             __func__, hba->saved_err, hba->saved_uic_err);
6045         }
6046         ufshcd_clear_eh_in_progress(hba);
6047         spin_unlock_irqrestore(hba->host->host_lock, flags);
6048         ufshcd_err_handling_unprepare(hba);
6049         up(&hba->host_sem);
6050 }
6051
6052 /**
6053  * ufshcd_update_uic_error - check and set fatal UIC error flags.
6054  * @hba: per-adapter instance
6055  *
6056  * Returns
6057  *  IRQ_HANDLED - If interrupt is valid
6058  *  IRQ_NONE    - If invalid interrupt
6059  */
6060 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6061 {
6062         u32 reg;
6063         irqreturn_t retval = IRQ_NONE;
6064
6065         /* PHY layer error */
6066         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6067         if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6068             (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6069                 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6070                 /*
6071                  * To know whether this error is fatal or not, DB timeout
6072                  * must be checked but this error is handled separately.
6073                  */
6074                 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6075                         dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6076                                         __func__);
6077
6078                 /* Got a LINERESET indication. */
6079                 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6080                         struct uic_command *cmd = NULL;
6081
6082                         hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6083                         if (hba->uic_async_done && hba->active_uic_cmd)
6084                                 cmd = hba->active_uic_cmd;
6085                         /*
6086                          * Ignore the LINERESET during power mode change
6087                          * operation via DME_SET command.
6088                          */
6089                         if (cmd && (cmd->command == UIC_CMD_DME_SET))
6090                                 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6091                 }
6092                 retval |= IRQ_HANDLED;
6093         }
6094
6095         /* PA_INIT_ERROR is fatal and needs UIC reset */
6096         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6097         if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6098             (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6099                 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6100
6101                 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6102                         hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6103                 else if (hba->dev_quirks &
6104                                 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6105                         if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6106                                 hba->uic_error |=
6107                                         UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6108                         else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6109                                 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6110                 }
6111                 retval |= IRQ_HANDLED;
6112         }
6113
6114         /* UIC NL/TL/DME errors needs software retry */
6115         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6116         if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6117             (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6118                 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6119                 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6120                 retval |= IRQ_HANDLED;
6121         }
6122
6123         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6124         if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6125             (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6126                 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6127                 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6128                 retval |= IRQ_HANDLED;
6129         }
6130
6131         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6132         if ((reg & UIC_DME_ERROR) &&
6133             (reg & UIC_DME_ERROR_CODE_MASK)) {
6134                 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6135                 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6136                 retval |= IRQ_HANDLED;
6137         }
6138
6139         dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6140                         __func__, hba->uic_error);
6141         return retval;
6142 }
6143
6144 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
6145                                          u32 intr_mask)
6146 {
6147         if (!ufshcd_is_auto_hibern8_supported(hba) ||
6148             !ufshcd_is_auto_hibern8_enabled(hba))
6149                 return false;
6150
6151         if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
6152                 return false;
6153
6154         if (hba->active_uic_cmd &&
6155             (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
6156             hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
6157                 return false;
6158
6159         return true;
6160 }
6161
6162 /**
6163  * ufshcd_check_errors - Check for errors that need s/w attention
6164  * @hba: per-adapter instance
6165  *
6166  * Returns
6167  *  IRQ_HANDLED - If interrupt is valid
6168  *  IRQ_NONE    - If invalid interrupt
6169  */
6170 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6171 {
6172         bool queue_eh_work = false;
6173         irqreturn_t retval = IRQ_NONE;
6174
6175         if (hba->errors & INT_FATAL_ERRORS) {
6176                 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6177                                        hba->errors);
6178                 queue_eh_work = true;
6179         }
6180
6181         if (hba->errors & UIC_ERROR) {
6182                 hba->uic_error = 0;
6183                 retval = ufshcd_update_uic_error(hba);
6184                 if (hba->uic_error)
6185                         queue_eh_work = true;
6186         }
6187
6188         if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6189                 dev_err(hba->dev,
6190                         "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6191                         __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6192                         "Enter" : "Exit",
6193                         hba->errors, ufshcd_get_upmcrs(hba));
6194                 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6195                                        hba->errors);
6196                 ufshcd_set_link_broken(hba);
6197                 queue_eh_work = true;
6198         }
6199
6200         if (queue_eh_work) {
6201                 /*
6202                  * update the transfer error masks to sticky bits, let's do this
6203                  * irrespective of current ufshcd_state.
6204                  */
6205                 hba->saved_err |= hba->errors;
6206                 hba->saved_uic_err |= hba->uic_error;
6207
6208                 /* dump controller state before resetting */
6209                 if ((hba->saved_err &
6210                      (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6211                     (hba->saved_uic_err &&
6212                      (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6213                         dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6214                                         __func__, hba->saved_err,
6215                                         hba->saved_uic_err);
6216                         ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6217                                          "host_regs: ");
6218                         ufshcd_print_pwr_info(hba);
6219                 }
6220                 ufshcd_schedule_eh_work(hba);
6221                 retval |= IRQ_HANDLED;
6222         }
6223         /*
6224          * if (!queue_eh_work) -
6225          * Other errors are either non-fatal where host recovers
6226          * itself without s/w intervention or errors that will be
6227          * handled by the SCSI core layer.
6228          */
6229         return retval;
6230 }
6231
6232 struct ctm_info {
6233         struct ufs_hba  *hba;
6234         unsigned long   pending;
6235         unsigned int    ncpl;
6236 };
6237
6238 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6239 {
6240         struct ctm_info *const ci = priv;
6241         struct completion *c;
6242
6243         WARN_ON_ONCE(reserved);
6244         if (test_bit(req->tag, &ci->pending))
6245                 return true;
6246         ci->ncpl++;
6247         c = req->end_io_data;
6248         if (c)
6249                 complete(c);
6250         return true;
6251 }
6252
6253 /**
6254  * ufshcd_tmc_handler - handle task management function completion
6255  * @hba: per adapter instance
6256  *
6257  * Returns
6258  *  IRQ_HANDLED - If interrupt is valid
6259  *  IRQ_NONE    - If invalid interrupt
6260  */
6261 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6262 {
6263         struct request_queue *q = hba->tmf_queue;
6264         struct ctm_info ci = {
6265                 .hba     = hba,
6266                 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
6267         };
6268
6269         blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6270         return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6271 }
6272
6273 /**
6274  * ufshcd_sl_intr - Interrupt service routine
6275  * @hba: per adapter instance
6276  * @intr_status: contains interrupts generated by the controller
6277  *
6278  * Returns
6279  *  IRQ_HANDLED - If interrupt is valid
6280  *  IRQ_NONE    - If invalid interrupt
6281  */
6282 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6283 {
6284         irqreturn_t retval = IRQ_NONE;
6285
6286         hba->errors = UFSHCD_ERROR_MASK & intr_status;
6287
6288         if (ufshcd_is_auto_hibern8_error(hba, intr_status))
6289                 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
6290
6291         if (hba->errors)
6292                 retval |= ufshcd_check_errors(hba);
6293
6294         if (intr_status & UFSHCD_UIC_MASK)
6295                 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6296
6297         if (intr_status & UTP_TASK_REQ_COMPL)
6298                 retval |= ufshcd_tmc_handler(hba);
6299
6300         if (intr_status & UTP_TRANSFER_REQ_COMPL)
6301                 retval |= ufshcd_transfer_req_compl(hba);
6302
6303         return retval;
6304 }
6305
6306 /**
6307  * ufshcd_intr - Main interrupt service routine
6308  * @irq: irq number
6309  * @__hba: pointer to adapter instance
6310  *
6311  * Returns
6312  *  IRQ_HANDLED - If interrupt is valid
6313  *  IRQ_NONE    - If invalid interrupt
6314  */
6315 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6316 {
6317         u32 intr_status, enabled_intr_status = 0;
6318         irqreturn_t retval = IRQ_NONE;
6319         struct ufs_hba *hba = __hba;
6320         int retries = hba->nutrs;
6321
6322         spin_lock(hba->host->host_lock);
6323         intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6324         hba->ufs_stats.last_intr_status = intr_status;
6325         hba->ufs_stats.last_intr_ts = ktime_get();
6326
6327         /*
6328          * There could be max of hba->nutrs reqs in flight and in worst case
6329          * if the reqs get finished 1 by 1 after the interrupt status is
6330          * read, make sure we handle them by checking the interrupt status
6331          * again in a loop until we process all of the reqs before returning.
6332          */
6333         while (intr_status && retries--) {
6334                 enabled_intr_status =
6335                         intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6336                 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6337                 if (enabled_intr_status)
6338                         retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6339
6340                 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6341         }
6342
6343         if (enabled_intr_status && retval == IRQ_NONE &&
6344                                 !ufshcd_eh_in_progress(hba)) {
6345                 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6346                                         __func__,
6347                                         intr_status,
6348                                         hba->ufs_stats.last_intr_status,
6349                                         enabled_intr_status);
6350                 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6351         }
6352
6353         spin_unlock(hba->host->host_lock);
6354         return retval;
6355 }
6356
6357 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6358 {
6359         int err = 0;
6360         u32 mask = 1 << tag;
6361         unsigned long flags;
6362
6363         if (!test_bit(tag, &hba->outstanding_tasks))
6364                 goto out;
6365
6366         spin_lock_irqsave(hba->host->host_lock, flags);
6367         ufshcd_utmrl_clear(hba, tag);
6368         spin_unlock_irqrestore(hba->host->host_lock, flags);
6369
6370         /* poll for max. 1 sec to clear door bell register by h/w */
6371         err = ufshcd_wait_for_register(hba,
6372                         REG_UTP_TASK_REQ_DOOR_BELL,
6373                         mask, 0, 1000, 1000);
6374 out:
6375         return err;
6376 }
6377
6378 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6379                 struct utp_task_req_desc *treq, u8 tm_function)
6380 {
6381         struct request_queue *q = hba->tmf_queue;
6382         struct Scsi_Host *host = hba->host;
6383         DECLARE_COMPLETION_ONSTACK(wait);
6384         struct request *req;
6385         unsigned long flags;
6386         int task_tag, err;
6387
6388         /*
6389          * blk_get_request() is used here only to get a free tag.
6390          */
6391         req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6392         if (IS_ERR(req))
6393                 return PTR_ERR(req);
6394
6395         req->end_io_data = &wait;
6396         ufshcd_hold(hba, false);
6397
6398         spin_lock_irqsave(host->host_lock, flags);
6399         blk_mq_start_request(req);
6400
6401         task_tag = req->tag;
6402         treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6403
6404         memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6405         ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6406
6407         /* send command to the controller */
6408         __set_bit(task_tag, &hba->outstanding_tasks);
6409
6410         /* Make sure descriptors are ready before ringing the task doorbell */
6411         wmb();
6412
6413         ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6414         /* Make sure that doorbell is committed immediately */
6415         wmb();
6416
6417         spin_unlock_irqrestore(host->host_lock, flags);
6418
6419         ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6420
6421         /* wait until the task management command is completed */
6422         err = wait_for_completion_io_timeout(&wait,
6423                         msecs_to_jiffies(TM_CMD_TIMEOUT));
6424         if (!err) {
6425                 /*
6426                  * Make sure that ufshcd_compl_tm() does not trigger a
6427                  * use-after-free.
6428                  */
6429                 req->end_io_data = NULL;
6430                 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6431                 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6432                                 __func__, tm_function);
6433                 if (ufshcd_clear_tm_cmd(hba, task_tag))
6434                         dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6435                                         __func__, task_tag);
6436                 err = -ETIMEDOUT;
6437         } else {
6438                 err = 0;
6439                 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6440
6441                 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6442         }
6443
6444         spin_lock_irqsave(hba->host->host_lock, flags);
6445         __clear_bit(task_tag, &hba->outstanding_tasks);
6446         spin_unlock_irqrestore(hba->host->host_lock, flags);
6447
6448         ufshcd_release(hba);
6449         blk_put_request(req);
6450
6451         return err;
6452 }
6453
6454 /**
6455  * ufshcd_issue_tm_cmd - issues task management commands to controller
6456  * @hba: per adapter instance
6457  * @lun_id: LUN ID to which TM command is sent
6458  * @task_id: task ID to which the TM command is applicable
6459  * @tm_function: task management function opcode
6460  * @tm_response: task management service response return value
6461  *
6462  * Returns non-zero value on error, zero on success.
6463  */
6464 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6465                 u8 tm_function, u8 *tm_response)
6466 {
6467         struct utp_task_req_desc treq = { { 0 }, };
6468         int ocs_value, err;
6469
6470         /* Configure task request descriptor */
6471         treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6472         treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6473
6474         /* Configure task request UPIU */
6475         treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6476                                   cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6477         treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6478
6479         /*
6480          * The host shall provide the same value for LUN field in the basic
6481          * header and for Input Parameter.
6482          */
6483         treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6484         treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6485
6486         err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6487         if (err == -ETIMEDOUT)
6488                 return err;
6489
6490         ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6491         if (ocs_value != OCS_SUCCESS)
6492                 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6493                                 __func__, ocs_value);
6494         else if (tm_response)
6495                 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6496                                 MASK_TM_SERVICE_RESP;
6497         return err;
6498 }
6499
6500 /**
6501  * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6502  * @hba:        per-adapter instance
6503  * @req_upiu:   upiu request
6504  * @rsp_upiu:   upiu reply
6505  * @desc_buff:  pointer to descriptor buffer, NULL if NA
6506  * @buff_len:   descriptor size, 0 if NA
6507  * @cmd_type:   specifies the type (NOP, Query...)
6508  * @desc_op:    descriptor operation
6509  *
6510  * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6511  * Therefore, it "rides" the device management infrastructure: uses its tag and
6512  * tasks work queues.
6513  *
6514  * Since there is only one available tag for device management commands,
6515  * the caller is expected to hold the hba->dev_cmd.lock mutex.
6516  */
6517 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6518                                         struct utp_upiu_req *req_upiu,
6519                                         struct utp_upiu_req *rsp_upiu,
6520                                         u8 *desc_buff, int *buff_len,
6521                                         enum dev_cmd_type cmd_type,
6522                                         enum query_opcode desc_op)
6523 {
6524         struct request_queue *q = hba->cmd_queue;
6525         struct request *req;
6526         struct ufshcd_lrb *lrbp;
6527         int err = 0;
6528         int tag;
6529         struct completion wait;
6530         unsigned long flags;
6531         u8 upiu_flags;
6532
6533         down_read(&hba->clk_scaling_lock);
6534
6535         req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6536         if (IS_ERR(req)) {
6537                 err = PTR_ERR(req);
6538                 goto out_unlock;
6539         }
6540         tag = req->tag;
6541         WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6542
6543         init_completion(&wait);
6544         lrbp = &hba->lrb[tag];
6545         if (unlikely(lrbp->in_use)) {
6546                 err = -EBUSY;
6547                 goto out;
6548         }
6549
6550         WARN_ON(lrbp->cmd);
6551         lrbp->cmd = NULL;
6552         lrbp->sense_bufflen = 0;
6553         lrbp->sense_buffer = NULL;
6554         lrbp->task_tag = tag;
6555         lrbp->lun = 0;
6556         lrbp->intr_cmd = true;
6557         ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6558         hba->dev_cmd.type = cmd_type;
6559
6560         if (hba->ufs_version <= ufshci_version(1, 1))
6561                 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6562         else
6563                 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6564
6565         /* update the task tag in the request upiu */
6566         req_upiu->header.dword_0 |= cpu_to_be32(tag);
6567
6568         ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6569
6570         /* just copy the upiu request as it is */
6571         memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6572         if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6573                 /* The Data Segment Area is optional depending upon the query
6574                  * function value. for WRITE DESCRIPTOR, the data segment
6575                  * follows right after the tsf.
6576                  */
6577                 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6578                 *buff_len = 0;
6579         }
6580
6581         memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6582
6583         hba->dev_cmd.complete = &wait;
6584
6585         /* Make sure descriptors are ready before ringing the doorbell */
6586         wmb();
6587         spin_lock_irqsave(hba->host->host_lock, flags);
6588         ufshcd_send_command(hba, tag);
6589         spin_unlock_irqrestore(hba->host->host_lock, flags);
6590
6591         /*
6592          * ignore the returning value here - ufshcd_check_query_response is
6593          * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6594          * read the response directly ignoring all errors.
6595          */
6596         ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6597
6598         /* just copy the upiu response as it is */
6599         memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6600         if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6601                 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6602                 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6603                                MASK_QUERY_DATA_SEG_LEN;
6604
6605                 if (*buff_len >= resp_len) {
6606                         memcpy(desc_buff, descp, resp_len);
6607                         *buff_len = resp_len;
6608                 } else {
6609                         dev_warn(hba->dev,
6610                                  "%s: rsp size %d is bigger than buffer size %d",
6611                                  __func__, resp_len, *buff_len);
6612                         *buff_len = 0;
6613                         err = -EINVAL;
6614                 }
6615         }
6616
6617 out:
6618         blk_put_request(req);
6619 out_unlock:
6620         up_read(&hba->clk_scaling_lock);
6621         return err;
6622 }
6623
6624 /**
6625  * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6626  * @hba:        per-adapter instance
6627  * @req_upiu:   upiu request
6628  * @rsp_upiu:   upiu reply - only 8 DW as we do not support scsi commands
6629  * @msgcode:    message code, one of UPIU Transaction Codes Initiator to Target
6630  * @desc_buff:  pointer to descriptor buffer, NULL if NA
6631  * @buff_len:   descriptor size, 0 if NA
6632  * @desc_op:    descriptor operation
6633  *
6634  * Supports UTP Transfer requests (nop and query), and UTP Task
6635  * Management requests.
6636  * It is up to the caller to fill the upiu conent properly, as it will
6637  * be copied without any further input validations.
6638  */
6639 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6640                              struct utp_upiu_req *req_upiu,
6641                              struct utp_upiu_req *rsp_upiu,
6642                              int msgcode,
6643                              u8 *desc_buff, int *buff_len,
6644                              enum query_opcode desc_op)
6645 {
6646         int err;
6647         enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6648         struct utp_task_req_desc treq = { { 0 }, };
6649         int ocs_value;
6650         u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6651
6652         switch (msgcode) {
6653         case UPIU_TRANSACTION_NOP_OUT:
6654                 cmd_type = DEV_CMD_TYPE_NOP;
6655                 fallthrough;
6656         case UPIU_TRANSACTION_QUERY_REQ:
6657                 ufshcd_hold(hba, false);
6658                 mutex_lock(&hba->dev_cmd.lock);
6659                 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6660                                                    desc_buff, buff_len,
6661                                                    cmd_type, desc_op);
6662                 mutex_unlock(&hba->dev_cmd.lock);
6663                 ufshcd_release(hba);
6664
6665                 break;
6666         case UPIU_TRANSACTION_TASK_REQ:
6667                 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6668                 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6669
6670                 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6671
6672                 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6673                 if (err == -ETIMEDOUT)
6674                         break;
6675
6676                 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6677                 if (ocs_value != OCS_SUCCESS) {
6678                         dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6679                                 ocs_value);
6680                         break;
6681                 }
6682
6683                 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6684
6685                 break;
6686         default:
6687                 err = -EINVAL;
6688
6689                 break;
6690         }
6691
6692         return err;
6693 }
6694
6695 /**
6696  * ufshcd_eh_device_reset_handler - device reset handler registered to
6697  *                                    scsi layer.
6698  * @cmd: SCSI command pointer
6699  *
6700  * Returns SUCCESS/FAILED
6701  */
6702 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6703 {
6704         struct Scsi_Host *host;
6705         struct ufs_hba *hba;
6706         u32 pos;
6707         int err;
6708         u8 resp = 0xF, lun;
6709         unsigned long flags;
6710
6711         host = cmd->device->host;
6712         hba = shost_priv(host);
6713
6714         lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6715         err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6716         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6717                 if (!err)
6718                         err = resp;
6719                 goto out;
6720         }
6721
6722         /* clear the commands that were pending for corresponding LUN */
6723         for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6724                 if (hba->lrb[pos].lun == lun) {
6725                         err = ufshcd_clear_cmd(hba, pos);
6726                         if (err)
6727                                 break;
6728                 }
6729         }
6730         spin_lock_irqsave(host->host_lock, flags);
6731         ufshcd_transfer_req_compl(hba);
6732         spin_unlock_irqrestore(host->host_lock, flags);
6733
6734 out:
6735         hba->req_abort_count = 0;
6736         ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6737         if (!err) {
6738                 err = SUCCESS;
6739         } else {
6740                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6741                 err = FAILED;
6742         }
6743         return err;
6744 }
6745
6746 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6747 {
6748         struct ufshcd_lrb *lrbp;
6749         int tag;
6750
6751         for_each_set_bit(tag, &bitmap, hba->nutrs) {
6752                 lrbp = &hba->lrb[tag];
6753                 lrbp->req_abort_skip = true;
6754         }
6755 }
6756
6757 /**
6758  * ufshcd_try_to_abort_task - abort a specific task
6759  * @hba: Pointer to adapter instance
6760  * @tag: Task tag/index to be aborted
6761  *
6762  * Abort the pending command in device by sending UFS_ABORT_TASK task management
6763  * command, and in host controller by clearing the door-bell register. There can
6764  * be race between controller sending the command to the device while abort is
6765  * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6766  * really issued and then try to abort it.
6767  *
6768  * Returns zero on success, non-zero on failure
6769  */
6770 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6771 {
6772         struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6773         int err = 0;
6774         int poll_cnt;
6775         u8 resp = 0xF;
6776         u32 reg;
6777
6778         for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6779                 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6780                                 UFS_QUERY_TASK, &resp);
6781                 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6782                         /* cmd pending in the device */
6783                         dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6784                                 __func__, tag);
6785                         break;
6786                 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6787                         /*
6788                          * cmd not pending in the device, check if it is
6789                          * in transition.
6790                          */
6791                         dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6792                                 __func__, tag);
6793                         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6794                         if (reg & (1 << tag)) {
6795                                 /* sleep for max. 200us to stabilize */
6796                                 usleep_range(100, 200);
6797                                 continue;
6798                         }
6799                         /* command completed already */
6800                         dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6801                                 __func__, tag);
6802                         goto out;
6803                 } else {
6804                         dev_err(hba->dev,
6805                                 "%s: no response from device. tag = %d, err %d\n",
6806                                 __func__, tag, err);
6807                         if (!err)
6808                                 err = resp; /* service response error */
6809                         goto out;
6810                 }
6811         }
6812
6813         if (!poll_cnt) {
6814                 err = -EBUSY;
6815                 goto out;
6816         }
6817
6818         err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6819                         UFS_ABORT_TASK, &resp);
6820         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6821                 if (!err) {
6822                         err = resp; /* service response error */
6823                         dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6824                                 __func__, tag, err);
6825                 }
6826                 goto out;
6827         }
6828
6829         err = ufshcd_clear_cmd(hba, tag);
6830         if (err)
6831                 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6832                         __func__, tag, err);
6833
6834 out:
6835         return err;
6836 }
6837
6838 /**
6839  * ufshcd_abort - scsi host template eh_abort_handler callback
6840  * @cmd: SCSI command pointer
6841  *
6842  * Returns SUCCESS/FAILED
6843  */
6844 static int ufshcd_abort(struct scsi_cmnd *cmd)
6845 {
6846         struct Scsi_Host *host;
6847         struct ufs_hba *hba;
6848         unsigned long flags;
6849         unsigned int tag;
6850         int err = 0;
6851         struct ufshcd_lrb *lrbp;
6852         u32 reg;
6853
6854         host = cmd->device->host;
6855         hba = shost_priv(host);
6856         tag = cmd->request->tag;
6857         lrbp = &hba->lrb[tag];
6858         if (!ufshcd_valid_tag(hba, tag)) {
6859                 dev_err(hba->dev,
6860                         "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6861                         __func__, tag, cmd, cmd->request);
6862                 BUG();
6863         }
6864
6865         ufshcd_hold(hba, false);
6866         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6867         /* If command is already aborted/completed, return SUCCESS */
6868         if (!(test_bit(tag, &hba->outstanding_reqs))) {
6869                 dev_err(hba->dev,
6870                         "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6871                         __func__, tag, hba->outstanding_reqs, reg);
6872                 goto out;
6873         }
6874
6875         /* Print Transfer Request of aborted task */
6876         dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6877
6878         /*
6879          * Print detailed info about aborted request.
6880          * As more than one request might get aborted at the same time,
6881          * print full information only for the first aborted request in order
6882          * to reduce repeated printouts. For other aborted requests only print
6883          * basic details.
6884          */
6885         scsi_print_command(cmd);
6886         if (!hba->req_abort_count) {
6887                 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
6888                 ufshcd_print_evt_hist(hba);
6889                 ufshcd_print_host_state(hba);
6890                 ufshcd_print_pwr_info(hba);
6891                 ufshcd_print_trs(hba, 1 << tag, true);
6892         } else {
6893                 ufshcd_print_trs(hba, 1 << tag, false);
6894         }
6895         hba->req_abort_count++;
6896
6897         if (!(reg & (1 << tag))) {
6898                 dev_err(hba->dev,
6899                 "%s: cmd was completed, but without a notifying intr, tag = %d",
6900                 __func__, tag);
6901                 goto cleanup;
6902         }
6903
6904         /*
6905          * Task abort to the device W-LUN is illegal. When this command
6906          * will fail, due to spec violation, scsi err handling next step
6907          * will be to send LU reset which, again, is a spec violation.
6908          * To avoid these unnecessary/illegal steps, first we clean up
6909          * the lrb taken by this cmd and mark the lrb as in_use, then
6910          * queue the eh_work and bail.
6911          */
6912         if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
6913                 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
6914                 spin_lock_irqsave(host->host_lock, flags);
6915                 if (lrbp->cmd) {
6916                         __ufshcd_transfer_req_compl(hba, (1UL << tag));
6917                         __set_bit(tag, &hba->outstanding_reqs);
6918                         lrbp->in_use = true;
6919                         hba->force_reset = true;
6920                         ufshcd_schedule_eh_work(hba);
6921                 }
6922
6923                 spin_unlock_irqrestore(host->host_lock, flags);
6924                 goto out;
6925         }
6926
6927         /* Skip task abort in case previous aborts failed and report failure */
6928         if (lrbp->req_abort_skip)
6929                 err = -EIO;
6930         else
6931                 err = ufshcd_try_to_abort_task(hba, tag);
6932
6933         if (!err) {
6934 cleanup:
6935                 spin_lock_irqsave(host->host_lock, flags);
6936                 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6937                 spin_unlock_irqrestore(host->host_lock, flags);
6938 out:
6939                 err = SUCCESS;
6940         } else {
6941                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6942                 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6943                 err = FAILED;
6944         }
6945
6946         /*
6947          * This ufshcd_release() corresponds to the original scsi cmd that got
6948          * aborted here (as we won't get any IRQ for it).
6949          */
6950         ufshcd_release(hba);
6951         return err;
6952 }
6953
6954 /**
6955  * ufshcd_host_reset_and_restore - reset and restore host controller
6956  * @hba: per-adapter instance
6957  *
6958  * Note that host controller reset may issue DME_RESET to
6959  * local and remote (device) Uni-Pro stack and the attributes
6960  * are reset to default state.
6961  *
6962  * Returns zero on success, non-zero on failure
6963  */
6964 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6965 {
6966         int err;
6967         unsigned long flags;
6968
6969         /*
6970          * Stop the host controller and complete the requests
6971          * cleared by h/w
6972          */
6973         ufshcd_hba_stop(hba);
6974
6975         spin_lock_irqsave(hba->host->host_lock, flags);
6976         hba->silence_err_logs = true;
6977         ufshcd_complete_requests(hba);
6978         hba->silence_err_logs = false;
6979         spin_unlock_irqrestore(hba->host->host_lock, flags);
6980
6981         /* scale up clocks to max frequency before full reinitialization */
6982         ufshcd_set_clk_freq(hba, true);
6983
6984         err = ufshcd_hba_enable(hba);
6985
6986         /* Establish the link again and restore the device */
6987         if (!err)
6988                 err = ufshcd_probe_hba(hba, false);
6989
6990         if (err)
6991                 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6992         ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
6993         return err;
6994 }
6995
6996 /**
6997  * ufshcd_reset_and_restore - reset and re-initialize host/device
6998  * @hba: per-adapter instance
6999  *
7000  * Reset and recover device, host and re-establish link. This
7001  * is helpful to recover the communication in fatal error conditions.
7002  *
7003  * Returns zero on success, non-zero on failure
7004  */
7005 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7006 {
7007         u32 saved_err;
7008         u32 saved_uic_err;
7009         int err = 0;
7010         unsigned long flags;
7011         int retries = MAX_HOST_RESET_RETRIES;
7012
7013         /*
7014          * This is a fresh start, cache and clear saved error first,
7015          * in case new error generated during reset and restore.
7016          */
7017         spin_lock_irqsave(hba->host->host_lock, flags);
7018         saved_err = hba->saved_err;
7019         saved_uic_err = hba->saved_uic_err;
7020         hba->saved_err = 0;
7021         hba->saved_uic_err = 0;
7022         spin_unlock_irqrestore(hba->host->host_lock, flags);
7023
7024         do {
7025                 /* Reset the attached device */
7026                 ufshcd_device_reset(hba);
7027
7028                 err = ufshcd_host_reset_and_restore(hba);
7029         } while (err && --retries);
7030
7031         spin_lock_irqsave(hba->host->host_lock, flags);
7032         /*
7033          * Inform scsi mid-layer that we did reset and allow to handle
7034          * Unit Attention properly.
7035          */
7036         scsi_report_bus_reset(hba->host, 0);
7037         if (err) {
7038                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7039                 hba->saved_err |= saved_err;
7040                 hba->saved_uic_err |= saved_uic_err;
7041         }
7042         spin_unlock_irqrestore(hba->host->host_lock, flags);
7043
7044         return err;
7045 }
7046
7047 /**
7048  * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7049  * @cmd: SCSI command pointer
7050  *
7051  * Returns SUCCESS/FAILED
7052  */
7053 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7054 {
7055         int err = SUCCESS;
7056         unsigned long flags;
7057         struct ufs_hba *hba;
7058
7059         hba = shost_priv(cmd->device->host);
7060
7061         spin_lock_irqsave(hba->host->host_lock, flags);
7062         hba->force_reset = true;
7063         ufshcd_schedule_eh_work(hba);
7064         dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7065         spin_unlock_irqrestore(hba->host->host_lock, flags);
7066
7067         flush_work(&hba->eh_work);
7068
7069         spin_lock_irqsave(hba->host->host_lock, flags);
7070         if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7071                 err = FAILED;
7072         spin_unlock_irqrestore(hba->host->host_lock, flags);
7073
7074         return err;
7075 }
7076
7077 /**
7078  * ufshcd_get_max_icc_level - calculate the ICC level
7079  * @sup_curr_uA: max. current supported by the regulator
7080  * @start_scan: row at the desc table to start scan from
7081  * @buff: power descriptor buffer
7082  *
7083  * Returns calculated max ICC level for specific regulator
7084  */
7085 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7086 {
7087         int i;
7088         int curr_uA;
7089         u16 data;
7090         u16 unit;
7091
7092         for (i = start_scan; i >= 0; i--) {
7093                 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7094                 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7095                                                 ATTR_ICC_LVL_UNIT_OFFSET;
7096                 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7097                 switch (unit) {
7098                 case UFSHCD_NANO_AMP:
7099                         curr_uA = curr_uA / 1000;
7100                         break;
7101                 case UFSHCD_MILI_AMP:
7102                         curr_uA = curr_uA * 1000;
7103                         break;
7104                 case UFSHCD_AMP:
7105                         curr_uA = curr_uA * 1000 * 1000;
7106                         break;
7107                 case UFSHCD_MICRO_AMP:
7108                 default:
7109                         break;
7110                 }
7111                 if (sup_curr_uA >= curr_uA)
7112                         break;
7113         }
7114         if (i < 0) {
7115                 i = 0;
7116                 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7117         }
7118
7119         return (u32)i;
7120 }
7121
7122 /**
7123  * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7124  * In case regulators are not initialized we'll return 0
7125  * @hba: per-adapter instance
7126  * @desc_buf: power descriptor buffer to extract ICC levels from.
7127  * @len: length of desc_buff
7128  *
7129  * Returns calculated ICC level
7130  */
7131 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7132                                                         u8 *desc_buf, int len)
7133 {
7134         u32 icc_level = 0;
7135
7136         if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7137                                                 !hba->vreg_info.vccq2) {
7138                 dev_err(hba->dev,
7139                         "%s: Regulator capability was not set, actvIccLevel=%d",
7140                                                         __func__, icc_level);
7141                 goto out;
7142         }
7143
7144         if (hba->vreg_info.vcc->max_uA)
7145                 icc_level = ufshcd_get_max_icc_level(
7146                                 hba->vreg_info.vcc->max_uA,
7147                                 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7148                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7149
7150         if (hba->vreg_info.vccq->max_uA)
7151                 icc_level = ufshcd_get_max_icc_level(
7152                                 hba->vreg_info.vccq->max_uA,
7153                                 icc_level,
7154                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7155
7156         if (hba->vreg_info.vccq2->max_uA)
7157                 icc_level = ufshcd_get_max_icc_level(
7158                                 hba->vreg_info.vccq2->max_uA,
7159                                 icc_level,
7160                                 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7161 out:
7162         return icc_level;
7163 }
7164
7165 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7166 {
7167         int ret;
7168         int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7169         u8 *desc_buf;
7170         u32 icc_level;
7171
7172         desc_buf = kmalloc(buff_len, GFP_KERNEL);
7173         if (!desc_buf)
7174                 return;
7175
7176         ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7177                                      desc_buf, buff_len);
7178         if (ret) {
7179                 dev_err(hba->dev,
7180                         "%s: Failed reading power descriptor.len = %d ret = %d",
7181                         __func__, buff_len, ret);
7182                 goto out;
7183         }
7184
7185         icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7186                                                          buff_len);
7187         dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7188
7189         ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7190                 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7191
7192         if (ret)
7193                 dev_err(hba->dev,
7194                         "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7195                         __func__, icc_level, ret);
7196
7197 out:
7198         kfree(desc_buf);
7199 }
7200
7201 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7202 {
7203         scsi_autopm_get_device(sdev);
7204         blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7205         if (sdev->rpm_autosuspend)
7206                 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7207                                                  RPM_AUTOSUSPEND_DELAY_MS);
7208         scsi_autopm_put_device(sdev);
7209 }
7210
7211 /**
7212  * ufshcd_scsi_add_wlus - Adds required W-LUs
7213  * @hba: per-adapter instance
7214  *
7215  * UFS device specification requires the UFS devices to support 4 well known
7216  * logical units:
7217  *      "REPORT_LUNS" (address: 01h)
7218  *      "UFS Device" (address: 50h)
7219  *      "RPMB" (address: 44h)
7220  *      "BOOT" (address: 30h)
7221  * UFS device's power management needs to be controlled by "POWER CONDITION"
7222  * field of SSU (START STOP UNIT) command. But this "power condition" field
7223  * will take effect only when its sent to "UFS device" well known logical unit
7224  * hence we require the scsi_device instance to represent this logical unit in
7225  * order for the UFS host driver to send the SSU command for power management.
7226  *
7227  * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7228  * Block) LU so user space process can control this LU. User space may also
7229  * want to have access to BOOT LU.
7230  *
7231  * This function adds scsi device instances for each of all well known LUs
7232  * (except "REPORT LUNS" LU).
7233  *
7234  * Returns zero on success (all required W-LUs are added successfully),
7235  * non-zero error value on failure (if failed to add any of the required W-LU).
7236  */
7237 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7238 {
7239         int ret = 0;
7240         struct scsi_device *sdev_boot;
7241
7242         hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7243                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7244         if (IS_ERR(hba->sdev_ufs_device)) {
7245                 ret = PTR_ERR(hba->sdev_ufs_device);
7246                 hba->sdev_ufs_device = NULL;
7247                 goto out;
7248         }
7249         ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
7250         scsi_device_put(hba->sdev_ufs_device);
7251
7252         hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7253                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7254         if (IS_ERR(hba->sdev_rpmb)) {
7255                 ret = PTR_ERR(hba->sdev_rpmb);
7256                 goto remove_sdev_ufs_device;
7257         }
7258         ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7259         scsi_device_put(hba->sdev_rpmb);
7260
7261         sdev_boot = __scsi_add_device(hba->host, 0, 0,
7262                 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7263         if (IS_ERR(sdev_boot)) {
7264                 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7265         } else {
7266                 ufshcd_blk_pm_runtime_init(sdev_boot);
7267                 scsi_device_put(sdev_boot);
7268         }
7269         goto out;
7270
7271 remove_sdev_ufs_device:
7272         scsi_remove_device(hba->sdev_ufs_device);
7273 out:
7274         return ret;
7275 }
7276
7277 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7278 {
7279         struct ufs_dev_info *dev_info = &hba->dev_info;
7280         u8 lun;
7281         u32 d_lu_wb_buf_alloc;
7282         u32 ext_ufs_feature;
7283
7284         if (!ufshcd_is_wb_allowed(hba))
7285                 return;
7286         /*
7287          * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7288          * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7289          * enabled
7290          */
7291         if (!(dev_info->wspecversion >= 0x310 ||
7292               dev_info->wspecversion == 0x220 ||
7293              (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7294                 goto wb_disabled;
7295
7296         if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7297             DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7298                 goto wb_disabled;
7299
7300         ext_ufs_feature = get_unaligned_be32(desc_buf +
7301                                         DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7302
7303         if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7304                 goto wb_disabled;
7305
7306         /*
7307          * WB may be supported but not configured while provisioning. The spec
7308          * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7309          * buffer configured.
7310          */
7311         dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7312
7313         dev_info->b_presrv_uspc_en =
7314                 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7315
7316         if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7317                 if (!get_unaligned_be32(desc_buf +
7318                                    DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7319                         goto wb_disabled;
7320         } else {
7321                 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7322                         d_lu_wb_buf_alloc = 0;
7323                         ufshcd_read_unit_desc_param(hba,
7324                                         lun,
7325                                         UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7326                                         (u8 *)&d_lu_wb_buf_alloc,
7327                                         sizeof(d_lu_wb_buf_alloc));
7328                         if (d_lu_wb_buf_alloc) {
7329                                 dev_info->wb_dedicated_lu = lun;
7330                                 break;
7331                         }
7332                 }
7333
7334                 if (!d_lu_wb_buf_alloc)
7335                         goto wb_disabled;
7336         }
7337         return;
7338
7339 wb_disabled:
7340         hba->caps &= ~UFSHCD_CAP_WB_EN;
7341 }
7342
7343 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7344 {
7345         struct ufs_dev_fix *f;
7346         struct ufs_dev_info *dev_info = &hba->dev_info;
7347
7348         if (!fixups)
7349                 return;
7350
7351         for (f = fixups; f->quirk; f++) {
7352                 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7353                      f->wmanufacturerid == UFS_ANY_VENDOR) &&
7354                      ((dev_info->model &&
7355                        STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7356                       !strcmp(f->model, UFS_ANY_MODEL)))
7357                         hba->dev_quirks |= f->quirk;
7358         }
7359 }
7360 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7361
7362 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7363 {
7364         /* fix by general quirk table */
7365         ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7366
7367         /* allow vendors to fix quirks */
7368         ufshcd_vops_fixup_dev_quirks(hba);
7369 }
7370
7371 static int ufs_get_device_desc(struct ufs_hba *hba)
7372 {
7373         int err;
7374         u8 model_index;
7375         u8 *desc_buf;
7376         struct ufs_dev_info *dev_info = &hba->dev_info;
7377
7378         desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7379         if (!desc_buf) {
7380                 err = -ENOMEM;
7381                 goto out;
7382         }
7383
7384         err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7385                                      hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7386         if (err) {
7387                 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7388                         __func__, err);
7389                 goto out;
7390         }
7391
7392         /*
7393          * getting vendor (manufacturerID) and Bank Index in big endian
7394          * format
7395          */
7396         dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7397                                      desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7398
7399         /* getting Specification Version in big endian format */
7400         dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7401                                       desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7402
7403         model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7404
7405         err = ufshcd_read_string_desc(hba, model_index,
7406                                       &dev_info->model, SD_ASCII_STD);
7407         if (err < 0) {
7408                 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7409                         __func__, err);
7410                 goto out;
7411         }
7412
7413         ufs_fixup_device_setup(hba);
7414
7415         ufshcd_wb_probe(hba, desc_buf);
7416
7417         /*
7418          * ufshcd_read_string_desc returns size of the string
7419          * reset the error value
7420          */
7421         err = 0;
7422
7423 out:
7424         kfree(desc_buf);
7425         return err;
7426 }
7427
7428 static void ufs_put_device_desc(struct ufs_hba *hba)
7429 {
7430         struct ufs_dev_info *dev_info = &hba->dev_info;
7431
7432         kfree(dev_info->model);
7433         dev_info->model = NULL;
7434 }
7435
7436 /**
7437  * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7438  * @hba: per-adapter instance
7439  *
7440  * PA_TActivate parameter can be tuned manually if UniPro version is less than
7441  * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7442  * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7443  * the hibern8 exit latency.
7444  *
7445  * Returns zero on success, non-zero error value on failure.
7446  */
7447 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7448 {
7449         int ret = 0;
7450         u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7451
7452         ret = ufshcd_dme_peer_get(hba,
7453                                   UIC_ARG_MIB_SEL(
7454                                         RX_MIN_ACTIVATETIME_CAPABILITY,
7455                                         UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7456                                   &peer_rx_min_activatetime);
7457         if (ret)
7458                 goto out;
7459
7460         /* make sure proper unit conversion is applied */
7461         tuned_pa_tactivate =
7462                 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7463                  / PA_TACTIVATE_TIME_UNIT_US);
7464         ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7465                              tuned_pa_tactivate);
7466
7467 out:
7468         return ret;
7469 }
7470
7471 /**
7472  * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7473  * @hba: per-adapter instance
7474  *
7475  * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7476  * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7477  * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7478  * This optimal value can help reduce the hibern8 exit latency.
7479  *
7480  * Returns zero on success, non-zero error value on failure.
7481  */
7482 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7483 {
7484         int ret = 0;
7485         u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7486         u32 max_hibern8_time, tuned_pa_hibern8time;
7487
7488         ret = ufshcd_dme_get(hba,
7489                              UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7490                                         UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7491                                   &local_tx_hibern8_time_cap);
7492         if (ret)
7493                 goto out;
7494
7495         ret = ufshcd_dme_peer_get(hba,
7496                                   UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7497                                         UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7498                                   &peer_rx_hibern8_time_cap);
7499         if (ret)
7500                 goto out;
7501
7502         max_hibern8_time = max(local_tx_hibern8_time_cap,
7503                                peer_rx_hibern8_time_cap);
7504         /* make sure proper unit conversion is applied */
7505         tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7506                                 / PA_HIBERN8_TIME_UNIT_US);
7507         ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7508                              tuned_pa_hibern8time);
7509 out:
7510         return ret;
7511 }
7512
7513 /**
7514  * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7515  * less than device PA_TACTIVATE time.
7516  * @hba: per-adapter instance
7517  *
7518  * Some UFS devices require host PA_TACTIVATE to be lower than device
7519  * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7520  * for such devices.
7521  *
7522  * Returns zero on success, non-zero error value on failure.
7523  */
7524 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7525 {
7526         int ret = 0;
7527         u32 granularity, peer_granularity;
7528         u32 pa_tactivate, peer_pa_tactivate;
7529         u32 pa_tactivate_us, peer_pa_tactivate_us;
7530         u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7531
7532         ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7533                                   &granularity);
7534         if (ret)
7535                 goto out;
7536
7537         ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7538                                   &peer_granularity);
7539         if (ret)
7540                 goto out;
7541
7542         if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7543             (granularity > PA_GRANULARITY_MAX_VAL)) {
7544                 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7545                         __func__, granularity);
7546                 return -EINVAL;
7547         }
7548
7549         if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7550             (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7551                 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7552                         __func__, peer_granularity);
7553                 return -EINVAL;
7554         }
7555
7556         ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7557         if (ret)
7558                 goto out;
7559
7560         ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7561                                   &peer_pa_tactivate);
7562         if (ret)
7563                 goto out;
7564
7565         pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7566         peer_pa_tactivate_us = peer_pa_tactivate *
7567                              gran_to_us_table[peer_granularity - 1];
7568
7569         if (pa_tactivate_us > peer_pa_tactivate_us) {
7570                 u32 new_peer_pa_tactivate;
7571
7572                 new_peer_pa_tactivate = pa_tactivate_us /
7573                                       gran_to_us_table[peer_granularity - 1];
7574                 new_peer_pa_tactivate++;
7575                 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7576                                           new_peer_pa_tactivate);
7577         }
7578
7579 out:
7580         return ret;
7581 }
7582
7583 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7584 {
7585         if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7586                 ufshcd_tune_pa_tactivate(hba);
7587                 ufshcd_tune_pa_hibern8time(hba);
7588         }
7589
7590         ufshcd_vops_apply_dev_quirks(hba);
7591
7592         if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7593                 /* set 1ms timeout for PA_TACTIVATE */
7594                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7595
7596         if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7597                 ufshcd_quirk_tune_host_pa_tactivate(hba);
7598 }
7599
7600 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7601 {
7602         hba->ufs_stats.hibern8_exit_cnt = 0;
7603         hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7604         hba->req_abort_count = 0;
7605 }
7606
7607 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7608 {
7609         int err;
7610         size_t buff_len;
7611         u8 *desc_buf;
7612
7613         buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7614         desc_buf = kmalloc(buff_len, GFP_KERNEL);
7615         if (!desc_buf) {
7616                 err = -ENOMEM;
7617                 goto out;
7618         }
7619
7620         err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7621                                      desc_buf, buff_len);
7622         if (err) {
7623                 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7624                                 __func__, err);
7625                 goto out;
7626         }
7627
7628         if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7629                 hba->dev_info.max_lu_supported = 32;
7630         else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7631                 hba->dev_info.max_lu_supported = 8;
7632
7633 out:
7634         kfree(desc_buf);
7635         return err;
7636 }
7637
7638 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7639         {19200000, REF_CLK_FREQ_19_2_MHZ},
7640         {26000000, REF_CLK_FREQ_26_MHZ},
7641         {38400000, REF_CLK_FREQ_38_4_MHZ},
7642         {52000000, REF_CLK_FREQ_52_MHZ},
7643         {0, REF_CLK_FREQ_INVAL},
7644 };
7645
7646 static enum ufs_ref_clk_freq
7647 ufs_get_bref_clk_from_hz(unsigned long freq)
7648 {
7649         int i;
7650
7651         for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7652                 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7653                         return ufs_ref_clk_freqs[i].val;
7654
7655         return REF_CLK_FREQ_INVAL;
7656 }
7657
7658 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7659 {
7660         unsigned long freq;
7661
7662         freq = clk_get_rate(refclk);
7663
7664         hba->dev_ref_clk_freq =
7665                 ufs_get_bref_clk_from_hz(freq);
7666
7667         if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7668                 dev_err(hba->dev,
7669                 "invalid ref_clk setting = %ld\n", freq);
7670 }
7671
7672 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7673 {
7674         int err;
7675         u32 ref_clk;
7676         u32 freq = hba->dev_ref_clk_freq;
7677
7678         err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7679                         QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7680
7681         if (err) {
7682                 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7683                         err);
7684                 goto out;
7685         }
7686
7687         if (ref_clk == freq)
7688                 goto out; /* nothing to update */
7689
7690         err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7691                         QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7692
7693         if (err) {
7694                 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7695                         ufs_ref_clk_freqs[freq].freq_hz);
7696                 goto out;
7697         }
7698
7699         dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7700                         ufs_ref_clk_freqs[freq].freq_hz);
7701
7702 out:
7703         return err;
7704 }
7705
7706 static int ufshcd_device_params_init(struct ufs_hba *hba)
7707 {
7708         bool flag;
7709         int ret, i;
7710
7711          /* Init device descriptor sizes */
7712         for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7713                 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7714
7715         /* Init UFS geometry descriptor related parameters */
7716         ret = ufshcd_device_geo_params_init(hba);
7717         if (ret)
7718                 goto out;
7719
7720         /* Check and apply UFS device quirks */
7721         ret = ufs_get_device_desc(hba);
7722         if (ret) {
7723                 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7724                         __func__, ret);
7725                 goto out;
7726         }
7727
7728         ufshcd_get_ref_clk_gating_wait(hba);
7729
7730         if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7731                         QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7732                 hba->dev_info.f_power_on_wp_en = flag;
7733
7734         /* Probe maximum power mode co-supported by both UFS host and device */
7735         if (ufshcd_get_max_pwr_mode(hba))
7736                 dev_err(hba->dev,
7737                         "%s: Failed getting max supported power mode\n",
7738                         __func__);
7739 out:
7740         return ret;
7741 }
7742
7743 /**
7744  * ufshcd_add_lus - probe and add UFS logical units
7745  * @hba: per-adapter instance
7746  */
7747 static int ufshcd_add_lus(struct ufs_hba *hba)
7748 {
7749         int ret;
7750
7751         /* Add required well known logical units to scsi mid layer */
7752         ret = ufshcd_scsi_add_wlus(hba);
7753         if (ret)
7754                 goto out;
7755
7756         ufshcd_clear_ua_wluns(hba);
7757
7758         /* Initialize devfreq after UFS device is detected */
7759         if (ufshcd_is_clkscaling_supported(hba)) {
7760                 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7761                         &hba->pwr_info,
7762                         sizeof(struct ufs_pa_layer_attr));
7763                 hba->clk_scaling.saved_pwr_info.is_valid = true;
7764                 hba->clk_scaling.is_allowed = true;
7765
7766                 ret = ufshcd_devfreq_init(hba);
7767                 if (ret)
7768                         goto out;
7769
7770                 hba->clk_scaling.is_enabled = true;
7771                 ufshcd_init_clk_scaling_sysfs(hba);
7772         }
7773
7774         ufs_bsg_probe(hba);
7775         scsi_scan_host(hba->host);
7776         pm_runtime_put_sync(hba->dev);
7777
7778 out:
7779         return ret;
7780 }
7781
7782 static int
7783 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7784
7785 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7786 {
7787         struct scsi_device *sdp;
7788         unsigned long flags;
7789         int ret = 0;
7790
7791         spin_lock_irqsave(hba->host->host_lock, flags);
7792         if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7793                 sdp = hba->sdev_ufs_device;
7794         else if (wlun == UFS_UPIU_RPMB_WLUN)
7795                 sdp = hba->sdev_rpmb;
7796         else
7797                 BUG();
7798         if (sdp) {
7799                 ret = scsi_device_get(sdp);
7800                 if (!ret && !scsi_device_online(sdp)) {
7801                         ret = -ENODEV;
7802                         scsi_device_put(sdp);
7803                 }
7804         } else {
7805                 ret = -ENODEV;
7806         }
7807         spin_unlock_irqrestore(hba->host->host_lock, flags);
7808         if (ret)
7809                 goto out_err;
7810
7811         ret = ufshcd_send_request_sense(hba, sdp);
7812         scsi_device_put(sdp);
7813 out_err:
7814         if (ret)
7815                 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7816                                 __func__, wlun, ret);
7817         return ret;
7818 }
7819
7820 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7821 {
7822         int ret = 0;
7823
7824         if (!hba->wlun_dev_clr_ua)
7825                 goto out;
7826
7827         ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7828         if (!ret)
7829                 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7830         if (!ret)
7831                 hba->wlun_dev_clr_ua = false;
7832 out:
7833         if (ret)
7834                 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
7835                                 __func__, ret);
7836         return ret;
7837 }
7838
7839 /**
7840  * ufshcd_probe_hba - probe hba to detect device and initialize
7841  * @hba: per-adapter instance
7842  * @async: asynchronous execution or not
7843  *
7844  * Execute link-startup and verify device initialization
7845  */
7846 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7847 {
7848         int ret;
7849         unsigned long flags;
7850         ktime_t start = ktime_get();
7851
7852         hba->ufshcd_state = UFSHCD_STATE_RESET;
7853
7854         ret = ufshcd_link_startup(hba);
7855         if (ret)
7856                 goto out;
7857
7858         /* Debug counters initialization */
7859         ufshcd_clear_dbg_ufs_stats(hba);
7860
7861         /* UniPro link is active now */
7862         ufshcd_set_link_active(hba);
7863
7864         /* Verify device initialization by sending NOP OUT UPIU */
7865         ret = ufshcd_verify_dev_init(hba);
7866         if (ret)
7867                 goto out;
7868
7869         /* Initiate UFS initialization, and waiting until completion */
7870         ret = ufshcd_complete_dev_init(hba);
7871         if (ret)
7872                 goto out;
7873
7874         /*
7875          * Initialize UFS device parameters used by driver, these
7876          * parameters are associated with UFS descriptors.
7877          */
7878         if (async) {
7879                 ret = ufshcd_device_params_init(hba);
7880                 if (ret)
7881                         goto out;
7882         }
7883
7884         ufshcd_tune_unipro_params(hba);
7885
7886         /* UFS device is also active now */
7887         ufshcd_set_ufs_dev_active(hba);
7888         ufshcd_force_reset_auto_bkops(hba);
7889         hba->wlun_dev_clr_ua = true;
7890
7891         /* Gear up to HS gear if supported */
7892         if (hba->max_pwr_info.is_valid) {
7893                 /*
7894                  * Set the right value to bRefClkFreq before attempting to
7895                  * switch to HS gears.
7896                  */
7897                 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7898                         ufshcd_set_dev_ref_clk(hba);
7899                 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7900                 if (ret) {
7901                         dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7902                                         __func__, ret);
7903                         goto out;
7904                 }
7905                 ufshcd_print_pwr_info(hba);
7906         }
7907
7908         /*
7909          * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7910          * and for removable UFS card as well, hence always set the parameter.
7911          * Note: Error handler may issue the device reset hence resetting
7912          * bActiveICCLevel as well so it is always safe to set this here.
7913          */
7914         ufshcd_set_active_icc_lvl(hba);
7915
7916         ufshcd_wb_config(hba);
7917         if (hba->ee_usr_mask)
7918                 ufshcd_write_ee_control(hba);
7919         /* Enable Auto-Hibernate if configured */
7920         ufshcd_auto_hibern8_enable(hba);
7921
7922 out:
7923         spin_lock_irqsave(hba->host->host_lock, flags);
7924         if (ret)
7925                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7926         else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7927                 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7928         spin_unlock_irqrestore(hba->host->host_lock, flags);
7929
7930         trace_ufshcd_init(dev_name(hba->dev), ret,
7931                 ktime_to_us(ktime_sub(ktime_get(), start)),
7932                 hba->curr_dev_pwr_mode, hba->uic_link_state);
7933         return ret;
7934 }
7935
7936 /**
7937  * ufshcd_async_scan - asynchronous execution for probing hba
7938  * @data: data pointer to pass to this function
7939  * @cookie: cookie data
7940  */
7941 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7942 {
7943         struct ufs_hba *hba = (struct ufs_hba *)data;
7944         int ret;
7945
7946         down(&hba->host_sem);
7947         /* Initialize hba, detect and initialize UFS device */
7948         ret = ufshcd_probe_hba(hba, true);
7949         up(&hba->host_sem);
7950         if (ret)
7951                 goto out;
7952
7953         /* Probe and add UFS logical units  */
7954         ret = ufshcd_add_lus(hba);
7955 out:
7956         /*
7957          * If we failed to initialize the device or the device is not
7958          * present, turn off the power/clocks etc.
7959          */
7960         if (ret) {
7961                 pm_runtime_put_sync(hba->dev);
7962                 ufshcd_hba_exit(hba);
7963         }
7964 }
7965
7966 static const struct attribute_group *ufshcd_driver_groups[] = {
7967         &ufs_sysfs_unit_descriptor_group,
7968         &ufs_sysfs_lun_attributes_group,
7969         NULL,
7970 };
7971
7972 static struct ufs_hba_variant_params ufs_hba_vps = {
7973         .hba_enable_delay_us            = 1000,
7974         .wb_flush_threshold             = UFS_WB_BUF_REMAIN_PERCENT(40),
7975         .devfreq_profile.polling_ms     = 100,
7976         .devfreq_profile.target         = ufshcd_devfreq_target,
7977         .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7978         .ondemand_data.upthreshold      = 70,
7979         .ondemand_data.downdifferential = 5,
7980 };
7981
7982 static struct scsi_host_template ufshcd_driver_template = {
7983         .module                 = THIS_MODULE,
7984         .name                   = UFSHCD,
7985         .proc_name              = UFSHCD,
7986         .queuecommand           = ufshcd_queuecommand,
7987         .slave_alloc            = ufshcd_slave_alloc,
7988         .slave_configure        = ufshcd_slave_configure,
7989         .slave_destroy          = ufshcd_slave_destroy,
7990         .change_queue_depth     = ufshcd_change_queue_depth,
7991         .eh_abort_handler       = ufshcd_abort,
7992         .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7993         .eh_host_reset_handler   = ufshcd_eh_host_reset_handler,
7994         .this_id                = -1,
7995         .sg_tablesize           = SG_ALL,
7996         .cmd_per_lun            = UFSHCD_CMD_PER_LUN,
7997         .can_queue              = UFSHCD_CAN_QUEUE,
7998         .max_segment_size       = PRDT_DATA_BYTE_COUNT_MAX,
7999         .max_host_blocked       = 1,
8000         .track_queue_depth      = 1,
8001         .sdev_groups            = ufshcd_driver_groups,
8002         .dma_boundary           = PAGE_SIZE - 1,
8003         .rpm_autosuspend_delay  = RPM_AUTOSUSPEND_DELAY_MS,
8004 };
8005
8006 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8007                                    int ua)
8008 {
8009         int ret;
8010
8011         if (!vreg)
8012                 return 0;
8013
8014         /*
8015          * "set_load" operation shall be required on those regulators
8016          * which specifically configured current limitation. Otherwise
8017          * zero max_uA may cause unexpected behavior when regulator is
8018          * enabled or set as high power mode.
8019          */
8020         if (!vreg->max_uA)
8021                 return 0;
8022
8023         ret = regulator_set_load(vreg->reg, ua);
8024         if (ret < 0) {
8025                 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8026                                 __func__, vreg->name, ua, ret);
8027         }
8028
8029         return ret;
8030 }
8031
8032 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8033                                          struct ufs_vreg *vreg)
8034 {
8035         return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8036 }
8037
8038 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8039                                          struct ufs_vreg *vreg)
8040 {
8041         if (!vreg)
8042                 return 0;
8043
8044         return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8045 }
8046
8047 static int ufshcd_config_vreg(struct device *dev,
8048                 struct ufs_vreg *vreg, bool on)
8049 {
8050         int ret = 0;
8051         struct regulator *reg;
8052         const char *name;
8053         int min_uV, uA_load;
8054
8055         BUG_ON(!vreg);
8056
8057         reg = vreg->reg;
8058         name = vreg->name;
8059
8060         if (regulator_count_voltages(reg) > 0) {
8061                 uA_load = on ? vreg->max_uA : 0;
8062                 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8063                 if (ret)
8064                         goto out;
8065
8066                 if (vreg->min_uV && vreg->max_uV) {
8067                         min_uV = on ? vreg->min_uV : 0;
8068                         ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8069                         if (ret)
8070                                 dev_err(dev,
8071                                         "%s: %s set voltage failed, err=%d\n",
8072                                         __func__, name, ret);
8073                 }
8074         }
8075 out:
8076         return ret;
8077 }
8078
8079 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8080 {
8081         int ret = 0;
8082
8083         if (!vreg || vreg->enabled)
8084                 goto out;
8085
8086         ret = ufshcd_config_vreg(dev, vreg, true);
8087         if (!ret)
8088                 ret = regulator_enable(vreg->reg);
8089
8090         if (!ret)
8091                 vreg->enabled = true;
8092         else
8093                 dev_err(dev, "%s: %s enable failed, err=%d\n",
8094                                 __func__, vreg->name, ret);
8095 out:
8096         return ret;
8097 }
8098
8099 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8100 {
8101         int ret = 0;
8102
8103         if (!vreg || !vreg->enabled || vreg->always_on)
8104                 goto out;
8105
8106         ret = regulator_disable(vreg->reg);
8107
8108         if (!ret) {
8109                 /* ignore errors on applying disable config */
8110                 ufshcd_config_vreg(dev, vreg, false);
8111                 vreg->enabled = false;
8112         } else {
8113                 dev_err(dev, "%s: %s disable failed, err=%d\n",
8114                                 __func__, vreg->name, ret);
8115         }
8116 out:
8117         return ret;
8118 }
8119
8120 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8121 {
8122         int ret = 0;
8123         struct device *dev = hba->dev;
8124         struct ufs_vreg_info *info = &hba->vreg_info;
8125
8126         ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8127         if (ret)
8128                 goto out;
8129
8130         ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8131         if (ret)
8132                 goto out;
8133
8134         ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8135
8136 out:
8137         if (ret) {
8138                 ufshcd_toggle_vreg(dev, info->vccq2, false);
8139                 ufshcd_toggle_vreg(dev, info->vccq, false);
8140                 ufshcd_toggle_vreg(dev, info->vcc, false);
8141         }
8142         return ret;
8143 }
8144
8145 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8146 {
8147         struct ufs_vreg_info *info = &hba->vreg_info;
8148
8149         return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8150 }
8151
8152 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8153 {
8154         int ret = 0;
8155
8156         if (!vreg)
8157                 goto out;
8158
8159         vreg->reg = devm_regulator_get(dev, vreg->name);
8160         if (IS_ERR(vreg->reg)) {
8161                 ret = PTR_ERR(vreg->reg);
8162                 dev_err(dev, "%s: %s get failed, err=%d\n",
8163                                 __func__, vreg->name, ret);
8164         }
8165 out:
8166         return ret;
8167 }
8168
8169 static int ufshcd_init_vreg(struct ufs_hba *hba)
8170 {
8171         int ret = 0;
8172         struct device *dev = hba->dev;
8173         struct ufs_vreg_info *info = &hba->vreg_info;
8174
8175         ret = ufshcd_get_vreg(dev, info->vcc);
8176         if (ret)
8177                 goto out;
8178
8179         ret = ufshcd_get_vreg(dev, info->vccq);
8180         if (!ret)
8181                 ret = ufshcd_get_vreg(dev, info->vccq2);
8182 out:
8183         return ret;
8184 }
8185
8186 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8187 {
8188         struct ufs_vreg_info *info = &hba->vreg_info;
8189
8190         if (info)
8191                 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8192
8193         return 0;
8194 }
8195
8196 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8197 {
8198         int ret = 0;
8199         struct ufs_clk_info *clki;
8200         struct list_head *head = &hba->clk_list_head;
8201         unsigned long flags;
8202         ktime_t start = ktime_get();
8203         bool clk_state_changed = false;
8204
8205         if (list_empty(head))
8206                 goto out;
8207
8208         ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8209         if (ret)
8210                 return ret;
8211
8212         list_for_each_entry(clki, head, list) {
8213                 if (!IS_ERR_OR_NULL(clki->clk)) {
8214                         /*
8215                          * Don't disable clocks which are needed
8216                          * to keep the link active.
8217                          */
8218                         if (ufshcd_is_link_active(hba) &&
8219                             clki->keep_link_active)
8220                                 continue;
8221
8222                         clk_state_changed = on ^ clki->enabled;
8223                         if (on && !clki->enabled) {
8224                                 ret = clk_prepare_enable(clki->clk);
8225                                 if (ret) {
8226                                         dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8227                                                 __func__, clki->name, ret);
8228                                         goto out;
8229                                 }
8230                         } else if (!on && clki->enabled) {
8231                                 clk_disable_unprepare(clki->clk);
8232                         }
8233                         clki->enabled = on;
8234                         dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8235                                         clki->name, on ? "en" : "dis");
8236                 }
8237         }
8238
8239         ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8240         if (ret)
8241                 return ret;
8242
8243 out:
8244         if (ret) {
8245                 list_for_each_entry(clki, head, list) {
8246                         if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8247                                 clk_disable_unprepare(clki->clk);
8248                 }
8249         } else if (!ret && on) {
8250                 spin_lock_irqsave(hba->host->host_lock, flags);
8251                 hba->clk_gating.state = CLKS_ON;
8252                 trace_ufshcd_clk_gating(dev_name(hba->dev),
8253                                         hba->clk_gating.state);
8254                 spin_unlock_irqrestore(hba->host->host_lock, flags);
8255         }
8256
8257         if (clk_state_changed)
8258                 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8259                         (on ? "on" : "off"),
8260                         ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8261         return ret;
8262 }
8263
8264 static int ufshcd_init_clocks(struct ufs_hba *hba)
8265 {
8266         int ret = 0;
8267         struct ufs_clk_info *clki;
8268         struct device *dev = hba->dev;
8269         struct list_head *head = &hba->clk_list_head;
8270
8271         if (list_empty(head))
8272                 goto out;
8273
8274         list_for_each_entry(clki, head, list) {
8275                 if (!clki->name)
8276                         continue;
8277
8278                 clki->clk = devm_clk_get(dev, clki->name);
8279                 if (IS_ERR(clki->clk)) {
8280                         ret = PTR_ERR(clki->clk);
8281                         dev_err(dev, "%s: %s clk get failed, %d\n",
8282                                         __func__, clki->name, ret);
8283                         goto out;
8284                 }
8285
8286                 /*
8287                  * Parse device ref clk freq as per device tree "ref_clk".
8288                  * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8289                  * in ufshcd_alloc_host().
8290                  */
8291                 if (!strcmp(clki->name, "ref_clk"))
8292                         ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8293
8294                 if (clki->max_freq) {
8295                         ret = clk_set_rate(clki->clk, clki->max_freq);
8296                         if (ret) {
8297                                 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8298                                         __func__, clki->name,
8299                                         clki->max_freq, ret);
8300                                 goto out;
8301                         }
8302                         clki->curr_freq = clki->max_freq;
8303                 }
8304                 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8305                                 clki->name, clk_get_rate(clki->clk));
8306         }
8307 out:
8308         return ret;
8309 }
8310
8311 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8312 {
8313         int err = 0;
8314
8315         if (!hba->vops)
8316                 goto out;
8317
8318         err = ufshcd_vops_init(hba);
8319         if (err)
8320                 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8321                         __func__, ufshcd_get_var_name(hba), err);
8322 out:
8323         return err;
8324 }
8325
8326 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8327 {
8328         if (!hba->vops)
8329                 return;
8330
8331         ufshcd_vops_exit(hba);
8332 }
8333
8334 static int ufshcd_hba_init(struct ufs_hba *hba)
8335 {
8336         int err;
8337
8338         /*
8339          * Handle host controller power separately from the UFS device power
8340          * rails as it will help controlling the UFS host controller power
8341          * collapse easily which is different than UFS device power collapse.
8342          * Also, enable the host controller power before we go ahead with rest
8343          * of the initialization here.
8344          */
8345         err = ufshcd_init_hba_vreg(hba);
8346         if (err)
8347                 goto out;
8348
8349         err = ufshcd_setup_hba_vreg(hba, true);
8350         if (err)
8351                 goto out;
8352
8353         err = ufshcd_init_clocks(hba);
8354         if (err)
8355                 goto out_disable_hba_vreg;
8356
8357         err = ufshcd_setup_clocks(hba, true);
8358         if (err)
8359                 goto out_disable_hba_vreg;
8360
8361         err = ufshcd_init_vreg(hba);
8362         if (err)
8363                 goto out_disable_clks;
8364
8365         err = ufshcd_setup_vreg(hba, true);
8366         if (err)
8367                 goto out_disable_clks;
8368
8369         err = ufshcd_variant_hba_init(hba);
8370         if (err)
8371                 goto out_disable_vreg;
8372
8373         ufs_debugfs_hba_init(hba);
8374
8375         hba->is_powered = true;
8376         goto out;
8377
8378 out_disable_vreg:
8379         ufshcd_setup_vreg(hba, false);
8380 out_disable_clks:
8381         ufshcd_setup_clocks(hba, false);
8382 out_disable_hba_vreg:
8383         ufshcd_setup_hba_vreg(hba, false);
8384 out:
8385         return err;
8386 }
8387
8388 static void ufshcd_hba_exit(struct ufs_hba *hba)
8389 {
8390         if (hba->is_powered) {
8391                 ufshcd_exit_clk_scaling(hba);
8392                 ufshcd_exit_clk_gating(hba);
8393                 if (hba->eh_wq)
8394                         destroy_workqueue(hba->eh_wq);
8395                 ufs_debugfs_hba_exit(hba);
8396                 ufshcd_variant_hba_exit(hba);
8397                 ufshcd_setup_vreg(hba, false);
8398                 ufshcd_setup_clocks(hba, false);
8399                 ufshcd_setup_hba_vreg(hba, false);
8400                 hba->is_powered = false;
8401                 ufs_put_device_desc(hba);
8402         }
8403 }
8404
8405 static int
8406 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8407 {
8408         unsigned char cmd[6] = {REQUEST_SENSE,
8409                                 0,
8410                                 0,
8411                                 0,
8412                                 UFS_SENSE_SIZE,
8413                                 0};
8414         char *buffer;
8415         int ret;
8416
8417         buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8418         if (!buffer) {
8419                 ret = -ENOMEM;
8420                 goto out;
8421         }
8422
8423         ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8424                         UFS_SENSE_SIZE, NULL, NULL,
8425                         msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8426         if (ret)
8427                 pr_err("%s: failed with err %d\n", __func__, ret);
8428
8429         kfree(buffer);
8430 out:
8431         return ret;
8432 }
8433
8434 /**
8435  * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8436  *                           power mode
8437  * @hba: per adapter instance
8438  * @pwr_mode: device power mode to set
8439  *
8440  * Returns 0 if requested power mode is set successfully
8441  * Returns non-zero if failed to set the requested power mode
8442  */
8443 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8444                                      enum ufs_dev_pwr_mode pwr_mode)
8445 {
8446         unsigned char cmd[6] = { START_STOP };
8447         struct scsi_sense_hdr sshdr;
8448         struct scsi_device *sdp;
8449         unsigned long flags;
8450         int ret;
8451
8452         spin_lock_irqsave(hba->host->host_lock, flags);
8453         sdp = hba->sdev_ufs_device;
8454         if (sdp) {
8455                 ret = scsi_device_get(sdp);
8456                 if (!ret && !scsi_device_online(sdp)) {
8457                         ret = -ENODEV;
8458                         scsi_device_put(sdp);
8459                 }
8460         } else {
8461                 ret = -ENODEV;
8462         }
8463         spin_unlock_irqrestore(hba->host->host_lock, flags);
8464
8465         if (ret)
8466                 return ret;
8467
8468         /*
8469          * If scsi commands fail, the scsi mid-layer schedules scsi error-
8470          * handling, which would wait for host to be resumed. Since we know
8471          * we are functional while we are here, skip host resume in error
8472          * handling context.
8473          */
8474         hba->host->eh_noresume = 1;
8475         ufshcd_clear_ua_wluns(hba);
8476
8477         cmd[4] = pwr_mode << 4;
8478
8479         /*
8480          * Current function would be generally called from the power management
8481          * callbacks hence set the RQF_PM flag so that it doesn't resume the
8482          * already suspended childs.
8483          */
8484         ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8485                         START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8486         if (ret) {
8487                 sdev_printk(KERN_WARNING, sdp,
8488                             "START_STOP failed for power mode: %d, result %x\n",
8489                             pwr_mode, ret);
8490                 if (driver_byte(ret) == DRIVER_SENSE)
8491                         scsi_print_sense_hdr(sdp, NULL, &sshdr);
8492         }
8493
8494         if (!ret)
8495                 hba->curr_dev_pwr_mode = pwr_mode;
8496
8497         scsi_device_put(sdp);
8498         hba->host->eh_noresume = 0;
8499         return ret;
8500 }
8501
8502 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8503                                         enum uic_link_state req_link_state,
8504                                         int check_for_bkops)
8505 {
8506         int ret = 0;
8507
8508         if (req_link_state == hba->uic_link_state)
8509                 return 0;
8510
8511         if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8512                 ret = ufshcd_uic_hibern8_enter(hba);
8513                 if (!ret) {
8514                         ufshcd_set_link_hibern8(hba);
8515                 } else {
8516                         dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8517                                         __func__, ret);
8518                         goto out;
8519                 }
8520         }
8521         /*
8522          * If autobkops is enabled, link can't be turned off because
8523          * turning off the link would also turn off the device, except in the
8524          * case of DeepSleep where the device is expected to remain powered.
8525          */
8526         else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8527                  (!check_for_bkops || !hba->auto_bkops_enabled)) {
8528                 /*
8529                  * Let's make sure that link is in low power mode, we are doing
8530                  * this currently by putting the link in Hibern8. Otherway to
8531                  * put the link in low power mode is to send the DME end point
8532                  * to device and then send the DME reset command to local
8533                  * unipro. But putting the link in hibern8 is much faster.
8534                  *
8535                  * Note also that putting the link in Hibern8 is a requirement
8536                  * for entering DeepSleep.
8537                  */
8538                 ret = ufshcd_uic_hibern8_enter(hba);
8539                 if (ret) {
8540                         dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8541                                         __func__, ret);
8542                         goto out;
8543                 }
8544                 /*
8545                  * Change controller state to "reset state" which
8546                  * should also put the link in off/reset state
8547                  */
8548                 ufshcd_hba_stop(hba);
8549                 /*
8550                  * TODO: Check if we need any delay to make sure that
8551                  * controller is reset
8552                  */
8553                 ufshcd_set_link_off(hba);
8554         }
8555
8556 out:
8557         return ret;
8558 }
8559
8560 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8561 {
8562         bool vcc_off = false;
8563
8564         /*
8565          * It seems some UFS devices may keep drawing more than sleep current
8566          * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8567          * To avoid this situation, add 2ms delay before putting these UFS
8568          * rails in LPM mode.
8569          */
8570         if (!ufshcd_is_link_active(hba) &&
8571             hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8572                 usleep_range(2000, 2100);
8573
8574         /*
8575          * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8576          * power.
8577          *
8578          * If UFS device and link is in OFF state, all power supplies (VCC,
8579          * VCCQ, VCCQ2) can be turned off if power on write protect is not
8580          * required. If UFS link is inactive (Hibern8 or OFF state) and device
8581          * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8582          *
8583          * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8584          * in low power state which would save some power.
8585          *
8586          * If Write Booster is enabled and the device needs to flush the WB
8587          * buffer OR if bkops status is urgent for WB, keep Vcc on.
8588          */
8589         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8590             !hba->dev_info.is_lu_power_on_wp) {
8591                 ufshcd_setup_vreg(hba, false);
8592                 vcc_off = true;
8593         } else if (!ufshcd_is_ufs_dev_active(hba)) {
8594                 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8595                 vcc_off = true;
8596                 if (!ufshcd_is_link_active(hba)) {
8597                         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8598                         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8599                 }
8600         }
8601
8602         /*
8603          * Some UFS devices require delay after VCC power rail is turned-off.
8604          */
8605         if (vcc_off && hba->vreg_info.vcc &&
8606                 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8607                 usleep_range(5000, 5100);
8608 }
8609
8610 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8611 {
8612         int ret = 0;
8613
8614         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8615             !hba->dev_info.is_lu_power_on_wp) {
8616                 ret = ufshcd_setup_vreg(hba, true);
8617         } else if (!ufshcd_is_ufs_dev_active(hba)) {
8618                 if (!ret && !ufshcd_is_link_active(hba)) {
8619                         ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8620                         if (ret)
8621                                 goto vcc_disable;
8622                         ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8623                         if (ret)
8624                                 goto vccq_lpm;
8625                 }
8626                 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8627         }
8628         goto out;
8629
8630 vccq_lpm:
8631         ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8632 vcc_disable:
8633         ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8634 out:
8635         return ret;
8636 }
8637
8638 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8639 {
8640         if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8641                 ufshcd_setup_hba_vreg(hba, false);
8642 }
8643
8644 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8645 {
8646         if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8647                 ufshcd_setup_hba_vreg(hba, true);
8648 }
8649
8650 /**
8651  * ufshcd_suspend - helper function for suspend operations
8652  * @hba: per adapter instance
8653  * @pm_op: desired low power operation type
8654  *
8655  * This function will try to put the UFS device and link into low power
8656  * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8657  * (System PM level).
8658  *
8659  * If this function is called during shutdown, it will make sure that
8660  * both UFS device and UFS link is powered off.
8661  *
8662  * NOTE: UFS device & link must be active before we enter in this function.
8663  *
8664  * Returns 0 for success and non-zero for failure
8665  */
8666 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8667 {
8668         int ret = 0;
8669         int check_for_bkops;
8670         enum ufs_pm_level pm_lvl;
8671         enum ufs_dev_pwr_mode req_dev_pwr_mode;
8672         enum uic_link_state req_link_state;
8673
8674         hba->pm_op_in_progress = 1;
8675         if (!ufshcd_is_shutdown_pm(pm_op)) {
8676                 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8677                          hba->rpm_lvl : hba->spm_lvl;
8678                 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8679                 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8680         } else {
8681                 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8682                 req_link_state = UIC_LINK_OFF_STATE;
8683         }
8684
8685         /*
8686          * If we can't transition into any of the low power modes
8687          * just gate the clocks.
8688          */
8689         ufshcd_hold(hba, false);
8690         hba->clk_gating.is_suspended = true;
8691
8692         if (ufshcd_is_clkscaling_supported(hba))
8693                 ufshcd_clk_scaling_suspend(hba, true);
8694
8695         if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8696                         req_link_state == UIC_LINK_ACTIVE_STATE) {
8697                 goto disable_clks;
8698         }
8699
8700         if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8701             (req_link_state == hba->uic_link_state))
8702                 goto enable_gating;
8703
8704         /* UFS device & link must be active before we enter in this function */
8705         if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8706                 ret = -EINVAL;
8707                 goto enable_gating;
8708         }
8709
8710         if (ufshcd_is_runtime_pm(pm_op)) {
8711                 if (ufshcd_can_autobkops_during_suspend(hba)) {
8712                         /*
8713                          * The device is idle with no requests in the queue,
8714                          * allow background operations if bkops status shows
8715                          * that performance might be impacted.
8716                          */
8717                         ret = ufshcd_urgent_bkops(hba);
8718                         if (ret)
8719                                 goto enable_gating;
8720                 } else {
8721                         /* make sure that auto bkops is disabled */
8722                         ufshcd_disable_auto_bkops(hba);
8723                 }
8724                 /*
8725                  * If device needs to do BKOP or WB buffer flush during
8726                  * Hibern8, keep device power mode as "active power mode"
8727                  * and VCC supply.
8728                  */
8729                 hba->dev_info.b_rpm_dev_flush_capable =
8730                         hba->auto_bkops_enabled ||
8731                         (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8732                         ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8733                         ufshcd_is_auto_hibern8_enabled(hba))) &&
8734                         ufshcd_wb_need_flush(hba));
8735         }
8736
8737         flush_work(&hba->eeh_work);
8738
8739         if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8740                 if (!ufshcd_is_runtime_pm(pm_op))
8741                         /* ensure that bkops is disabled */
8742                         ufshcd_disable_auto_bkops(hba);
8743
8744                 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8745                         ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8746                         if (ret)
8747                                 goto enable_gating;
8748                 }
8749         }
8750
8751         /*
8752          * In the case of DeepSleep, the device is expected to remain powered
8753          * with the link off, so do not check for bkops.
8754          */
8755         check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8756         ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8757         if (ret)
8758                 goto set_dev_active;
8759
8760 disable_clks:
8761         /*
8762          * Call vendor specific suspend callback. As these callbacks may access
8763          * vendor specific host controller register space call them before the
8764          * host clocks are ON.
8765          */
8766         ret = ufshcd_vops_suspend(hba, pm_op);
8767         if (ret)
8768                 goto set_link_active;
8769         /*
8770          * Disable the host irq as host controller as there won't be any
8771          * host controller transaction expected till resume.
8772          */
8773         ufshcd_disable_irq(hba);
8774
8775         ufshcd_setup_clocks(hba, false);
8776
8777         if (ufshcd_is_clkgating_allowed(hba)) {
8778                 hba->clk_gating.state = CLKS_OFF;
8779                 trace_ufshcd_clk_gating(dev_name(hba->dev),
8780                                         hba->clk_gating.state);
8781         }
8782
8783         ufshcd_vreg_set_lpm(hba);
8784
8785         /* Put the host controller in low power mode if possible */
8786         ufshcd_hba_vreg_set_lpm(hba);
8787         goto out;
8788
8789 set_link_active:
8790         ufshcd_vreg_set_hpm(hba);
8791         /*
8792          * Device hardware reset is required to exit DeepSleep. Also, for
8793          * DeepSleep, the link is off so host reset and restore will be done
8794          * further below.
8795          */
8796         if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8797                 ufshcd_device_reset(hba);
8798                 WARN_ON(!ufshcd_is_link_off(hba));
8799         }
8800         if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8801                 ufshcd_set_link_active(hba);
8802         else if (ufshcd_is_link_off(hba))
8803                 ufshcd_host_reset_and_restore(hba);
8804 set_dev_active:
8805         /* Can also get here needing to exit DeepSleep */
8806         if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8807                 ufshcd_device_reset(hba);
8808                 ufshcd_host_reset_and_restore(hba);
8809         }
8810         if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8811                 ufshcd_disable_auto_bkops(hba);
8812 enable_gating:
8813         if (ufshcd_is_clkscaling_supported(hba))
8814                 ufshcd_clk_scaling_suspend(hba, false);
8815
8816         hba->clk_gating.is_suspended = false;
8817         hba->dev_info.b_rpm_dev_flush_capable = false;
8818         ufshcd_clear_ua_wluns(hba);
8819         ufshcd_release(hba);
8820 out:
8821         if (hba->dev_info.b_rpm_dev_flush_capable) {
8822                 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8823                         msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8824         }
8825
8826         hba->pm_op_in_progress = 0;
8827
8828         if (ret)
8829                 ufshcd_update_evt_hist(hba, UFS_EVT_SUSPEND_ERR, (u32)ret);
8830         return ret;
8831 }
8832
8833 /**
8834  * ufshcd_resume - helper function for resume operations
8835  * @hba: per adapter instance
8836  * @pm_op: runtime PM or system PM
8837  *
8838  * This function basically brings the UFS device, UniPro link and controller
8839  * to active state.
8840  *
8841  * Returns 0 for success and non-zero for failure
8842  */
8843 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8844 {
8845         int ret;
8846         enum uic_link_state old_link_state;
8847
8848         hba->pm_op_in_progress = 1;
8849         old_link_state = hba->uic_link_state;
8850
8851         ufshcd_hba_vreg_set_hpm(hba);
8852         ret = ufshcd_vreg_set_hpm(hba);
8853         if (ret)
8854                 goto out;
8855
8856         /* Make sure clocks are enabled before accessing controller */
8857         ret = ufshcd_setup_clocks(hba, true);
8858         if (ret)
8859                 goto disable_vreg;
8860
8861         /* enable the host irq as host controller would be active soon */
8862         ufshcd_enable_irq(hba);
8863
8864         /*
8865          * Call vendor specific resume callback. As these callbacks may access
8866          * vendor specific host controller register space call them when the
8867          * host clocks are ON.
8868          */
8869         ret = ufshcd_vops_resume(hba, pm_op);
8870         if (ret)
8871                 goto disable_irq_and_vops_clks;
8872
8873         /* For DeepSleep, the only supported option is to have the link off */
8874         WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8875
8876         if (ufshcd_is_link_hibern8(hba)) {
8877                 ret = ufshcd_uic_hibern8_exit(hba);
8878                 if (!ret) {
8879                         ufshcd_set_link_active(hba);
8880                 } else {
8881                         dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8882                                         __func__, ret);
8883                         goto vendor_suspend;
8884                 }
8885         } else if (ufshcd_is_link_off(hba)) {
8886                 /*
8887                  * A full initialization of the host and the device is
8888                  * required since the link was put to off during suspend.
8889                  * Note, in the case of DeepSleep, the device will exit
8890                  * DeepSleep due to device reset.
8891                  */
8892                 ret = ufshcd_reset_and_restore(hba);
8893                 /*
8894                  * ufshcd_reset_and_restore() should have already
8895                  * set the link state as active
8896                  */
8897                 if (ret || !ufshcd_is_link_active(hba))
8898                         goto vendor_suspend;
8899         }
8900
8901         if (!ufshcd_is_ufs_dev_active(hba)) {
8902                 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8903                 if (ret)
8904                         goto set_old_link_state;
8905         }
8906
8907         if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8908                 ufshcd_enable_auto_bkops(hba);
8909         else
8910                 /*
8911                  * If BKOPs operations are urgently needed at this moment then
8912                  * keep auto-bkops enabled or else disable it.
8913                  */
8914                 ufshcd_urgent_bkops(hba);
8915
8916         if (hba->ee_usr_mask)
8917                 ufshcd_write_ee_control(hba);
8918
8919         hba->clk_gating.is_suspended = false;
8920
8921         if (ufshcd_is_clkscaling_supported(hba))
8922                 ufshcd_clk_scaling_suspend(hba, false);
8923
8924         /* Enable Auto-Hibernate if configured */
8925         ufshcd_auto_hibern8_enable(hba);
8926
8927         if (hba->dev_info.b_rpm_dev_flush_capable) {
8928                 hba->dev_info.b_rpm_dev_flush_capable = false;
8929                 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8930         }
8931
8932         ufshcd_clear_ua_wluns(hba);
8933
8934         /* Schedule clock gating in case of no access to UFS device yet */
8935         ufshcd_release(hba);
8936
8937         goto out;
8938
8939 set_old_link_state:
8940         ufshcd_link_state_transition(hba, old_link_state, 0);
8941 vendor_suspend:
8942         ufshcd_vops_suspend(hba, pm_op);
8943 disable_irq_and_vops_clks:
8944         ufshcd_disable_irq(hba);
8945         ufshcd_setup_clocks(hba, false);
8946         if (ufshcd_is_clkgating_allowed(hba)) {
8947                 hba->clk_gating.state = CLKS_OFF;
8948                 trace_ufshcd_clk_gating(dev_name(hba->dev),
8949                                         hba->clk_gating.state);
8950         }
8951 disable_vreg:
8952         ufshcd_vreg_set_lpm(hba);
8953 out:
8954         hba->pm_op_in_progress = 0;
8955         if (ret)
8956                 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
8957         return ret;
8958 }
8959
8960 /**
8961  * ufshcd_system_suspend - system suspend routine
8962  * @hba: per adapter instance
8963  *
8964  * Check the description of ufshcd_suspend() function for more details.
8965  *
8966  * Returns 0 for success and non-zero for failure
8967  */
8968 int ufshcd_system_suspend(struct ufs_hba *hba)
8969 {
8970         int ret = 0;
8971         ktime_t start = ktime_get();
8972
8973         down(&hba->host_sem);
8974
8975         if (!hba->is_powered)
8976                 return 0;
8977
8978         if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8979              hba->curr_dev_pwr_mode) &&
8980             (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8981              hba->uic_link_state) &&
8982              !hba->dev_info.b_rpm_dev_flush_capable)
8983                 goto out;
8984
8985         if (pm_runtime_suspended(hba->dev)) {
8986                 /*
8987                  * UFS device and/or UFS link low power states during runtime
8988                  * suspend seems to be different than what is expected during
8989                  * system suspend. Hence runtime resume the devic & link and
8990                  * let the system suspend low power states to take effect.
8991                  * TODO: If resume takes longer time, we might have optimize
8992                  * it in future by not resuming everything if possible.
8993                  */
8994                 ret = ufshcd_runtime_resume(hba);
8995                 if (ret)
8996                         goto out;
8997         }
8998
8999         ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
9000 out:
9001         trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9002                 ktime_to_us(ktime_sub(ktime_get(), start)),
9003                 hba->curr_dev_pwr_mode, hba->uic_link_state);
9004         if (!ret)
9005                 hba->is_sys_suspended = true;
9006         else
9007                 up(&hba->host_sem);
9008         return ret;
9009 }
9010 EXPORT_SYMBOL(ufshcd_system_suspend);
9011
9012 /**
9013  * ufshcd_system_resume - system resume routine
9014  * @hba: per adapter instance
9015  *
9016  * Returns 0 for success and non-zero for failure
9017  */
9018
9019 int ufshcd_system_resume(struct ufs_hba *hba)
9020 {
9021         int ret = 0;
9022         ktime_t start = ktime_get();
9023
9024         if (!hba->is_powered || pm_runtime_suspended(hba->dev))
9025                 /*
9026                  * Let the runtime resume take care of resuming
9027                  * if runtime suspended.
9028                  */
9029                 goto out;
9030         else
9031                 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
9032 out:
9033         trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9034                 ktime_to_us(ktime_sub(ktime_get(), start)),
9035                 hba->curr_dev_pwr_mode, hba->uic_link_state);
9036         if (!ret)
9037                 hba->is_sys_suspended = false;
9038         up(&hba->host_sem);
9039         return ret;
9040 }
9041 EXPORT_SYMBOL(ufshcd_system_resume);
9042
9043 /**
9044  * ufshcd_runtime_suspend - runtime suspend routine
9045  * @hba: per adapter instance
9046  *
9047  * Check the description of ufshcd_suspend() function for more details.
9048  *
9049  * Returns 0 for success and non-zero for failure
9050  */
9051 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9052 {
9053         int ret = 0;
9054         ktime_t start = ktime_get();
9055
9056         if (!hba->is_powered)
9057                 goto out;
9058         else
9059                 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9060 out:
9061         trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9062                 ktime_to_us(ktime_sub(ktime_get(), start)),
9063                 hba->curr_dev_pwr_mode, hba->uic_link_state);
9064         return ret;
9065 }
9066 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9067
9068 /**
9069  * ufshcd_runtime_resume - runtime resume routine
9070  * @hba: per adapter instance
9071  *
9072  * This function basically brings the UFS device, UniPro link and controller
9073  * to active state. Following operations are done in this function:
9074  *
9075  * 1. Turn on all the controller related clocks
9076  * 2. Bring the UniPro link out of Hibernate state
9077  * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9078  *    to active state.
9079  * 4. If auto-bkops is enabled on the device, disable it.
9080  *
9081  * So following would be the possible power state after this function return
9082  * successfully:
9083  *      S1: UFS device in Active state with VCC rail ON
9084  *          UniPro link in Active state
9085  *          All the UFS/UniPro controller clocks are ON
9086  *
9087  * Returns 0 for success and non-zero for failure
9088  */
9089 int ufshcd_runtime_resume(struct ufs_hba *hba)
9090 {
9091         int ret = 0;
9092         ktime_t start = ktime_get();
9093
9094         if (!hba->is_powered)
9095                 goto out;
9096         else
9097                 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9098 out:
9099         trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9100                 ktime_to_us(ktime_sub(ktime_get(), start)),
9101                 hba->curr_dev_pwr_mode, hba->uic_link_state);
9102         return ret;
9103 }
9104 EXPORT_SYMBOL(ufshcd_runtime_resume);
9105
9106 int ufshcd_runtime_idle(struct ufs_hba *hba)
9107 {
9108         return 0;
9109 }
9110 EXPORT_SYMBOL(ufshcd_runtime_idle);
9111
9112 /**
9113  * ufshcd_shutdown - shutdown routine
9114  * @hba: per adapter instance
9115  *
9116  * This function would power off both UFS device and UFS link.
9117  *
9118  * Returns 0 always to allow force shutdown even in case of errors.
9119  */
9120 int ufshcd_shutdown(struct ufs_hba *hba)
9121 {
9122         int ret = 0;
9123
9124         down(&hba->host_sem);
9125         hba->shutting_down = true;
9126         up(&hba->host_sem);
9127
9128         if (!hba->is_powered)
9129                 goto out;
9130
9131         if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9132                 goto out;
9133
9134         pm_runtime_get_sync(hba->dev);
9135
9136         ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9137 out:
9138         if (ret)
9139                 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9140         hba->is_powered = false;
9141         /* allow force shutdown even in case of errors */
9142         return 0;
9143 }
9144 EXPORT_SYMBOL(ufshcd_shutdown);
9145
9146 /**
9147  * ufshcd_remove - de-allocate SCSI host and host memory space
9148  *              data structure memory
9149  * @hba: per adapter instance
9150  */
9151 void ufshcd_remove(struct ufs_hba *hba)
9152 {
9153         ufs_bsg_remove(hba);
9154         ufs_sysfs_remove_nodes(hba->dev);
9155         blk_cleanup_queue(hba->tmf_queue);
9156         blk_mq_free_tag_set(&hba->tmf_tag_set);
9157         blk_cleanup_queue(hba->cmd_queue);
9158         scsi_remove_host(hba->host);
9159         /* disable interrupts */
9160         ufshcd_disable_intr(hba, hba->intr_mask);
9161         ufshcd_hba_stop(hba);
9162         ufshcd_hba_exit(hba);
9163 }
9164 EXPORT_SYMBOL_GPL(ufshcd_remove);
9165
9166 /**
9167  * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9168  * @hba: pointer to Host Bus Adapter (HBA)
9169  */
9170 void ufshcd_dealloc_host(struct ufs_hba *hba)
9171 {
9172         scsi_host_put(hba->host);
9173 }
9174 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9175
9176 /**
9177  * ufshcd_set_dma_mask - Set dma mask based on the controller
9178  *                       addressing capability
9179  * @hba: per adapter instance
9180  *
9181  * Returns 0 for success, non-zero for failure
9182  */
9183 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9184 {
9185         if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9186                 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9187                         return 0;
9188         }
9189         return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9190 }
9191
9192 /**
9193  * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9194  * @dev: pointer to device handle
9195  * @hba_handle: driver private handle
9196  * Returns 0 on success, non-zero value on failure
9197  */
9198 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9199 {
9200         struct Scsi_Host *host;
9201         struct ufs_hba *hba;
9202         int err = 0;
9203
9204         if (!dev) {
9205                 dev_err(dev,
9206                 "Invalid memory reference for dev is NULL\n");
9207                 err = -ENODEV;
9208                 goto out_error;
9209         }
9210
9211         host = scsi_host_alloc(&ufshcd_driver_template,
9212                                 sizeof(struct ufs_hba));
9213         if (!host) {
9214                 dev_err(dev, "scsi_host_alloc failed\n");
9215                 err = -ENOMEM;
9216                 goto out_error;
9217         }
9218         hba = shost_priv(host);
9219         hba->host = host;
9220         hba->dev = dev;
9221         *hba_handle = hba;
9222         hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9223
9224         INIT_LIST_HEAD(&hba->clk_list_head);
9225
9226 out_error:
9227         return err;
9228 }
9229 EXPORT_SYMBOL(ufshcd_alloc_host);
9230
9231 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9232 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9233                                      const struct blk_mq_queue_data *qd)
9234 {
9235         WARN_ON_ONCE(true);
9236         return BLK_STS_NOTSUPP;
9237 }
9238
9239 static const struct blk_mq_ops ufshcd_tmf_ops = {
9240         .queue_rq = ufshcd_queue_tmf,
9241 };
9242
9243 /**
9244  * ufshcd_init - Driver initialization routine
9245  * @hba: per-adapter instance
9246  * @mmio_base: base register address
9247  * @irq: Interrupt line of device
9248  * Returns 0 on success, non-zero value on failure
9249  */
9250 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9251 {
9252         int err;
9253         struct Scsi_Host *host = hba->host;
9254         struct device *dev = hba->dev;
9255         char eh_wq_name[sizeof("ufs_eh_wq_00")];
9256
9257         if (!mmio_base) {
9258                 dev_err(hba->dev,
9259                 "Invalid memory reference for mmio_base is NULL\n");
9260                 err = -ENODEV;
9261                 goto out_error;
9262         }
9263
9264         hba->mmio_base = mmio_base;
9265         hba->irq = irq;
9266         hba->vps = &ufs_hba_vps;
9267
9268         err = ufshcd_hba_init(hba);
9269         if (err)
9270                 goto out_error;
9271
9272         /* Read capabilities registers */
9273         err = ufshcd_hba_capabilities(hba);
9274         if (err)
9275                 goto out_disable;
9276
9277         /* Get UFS version supported by the controller */
9278         hba->ufs_version = ufshcd_get_ufs_version(hba);
9279
9280         /* Get Interrupt bit mask per version */
9281         hba->intr_mask = ufshcd_get_intr_mask(hba);
9282
9283         err = ufshcd_set_dma_mask(hba);
9284         if (err) {
9285                 dev_err(hba->dev, "set dma mask failed\n");
9286                 goto out_disable;
9287         }
9288
9289         /* Allocate memory for host memory space */
9290         err = ufshcd_memory_alloc(hba);
9291         if (err) {
9292                 dev_err(hba->dev, "Memory allocation failed\n");
9293                 goto out_disable;
9294         }
9295
9296         /* Configure LRB */
9297         ufshcd_host_memory_configure(hba);
9298
9299         host->can_queue = hba->nutrs;
9300         host->cmd_per_lun = hba->nutrs;
9301         host->max_id = UFSHCD_MAX_ID;
9302         host->max_lun = UFS_MAX_LUNS;
9303         host->max_channel = UFSHCD_MAX_CHANNEL;
9304         host->unique_id = host->host_no;
9305         host->max_cmd_len = UFS_CDB_SIZE;
9306
9307         hba->max_pwr_info.is_valid = false;
9308
9309         /* Initialize work queues */
9310         snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9311                  hba->host->host_no);
9312         hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9313         if (!hba->eh_wq) {
9314                 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9315                                 __func__);
9316                 err = -ENOMEM;
9317                 goto out_disable;
9318         }
9319         INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9320         INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9321
9322         sema_init(&hba->host_sem, 1);
9323
9324         /* Initialize UIC command mutex */
9325         mutex_init(&hba->uic_cmd_mutex);
9326
9327         /* Initialize mutex for device management commands */
9328         mutex_init(&hba->dev_cmd.lock);
9329
9330         /* Initialize mutex for exception event control */
9331         mutex_init(&hba->ee_ctrl_mutex);
9332
9333         init_rwsem(&hba->clk_scaling_lock);
9334
9335         ufshcd_init_clk_gating(hba);
9336
9337         ufshcd_init_clk_scaling(hba);
9338
9339         /*
9340          * In order to avoid any spurious interrupt immediately after
9341          * registering UFS controller interrupt handler, clear any pending UFS
9342          * interrupt status and disable all the UFS interrupts.
9343          */
9344         ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9345                       REG_INTERRUPT_STATUS);
9346         ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9347         /*
9348          * Make sure that UFS interrupts are disabled and any pending interrupt
9349          * status is cleared before registering UFS interrupt handler.
9350          */
9351         mb();
9352
9353         /* IRQ registration */
9354         err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9355         if (err) {
9356                 dev_err(hba->dev, "request irq failed\n");
9357                 goto out_disable;
9358         } else {
9359                 hba->is_irq_enabled = true;
9360         }
9361
9362         err = scsi_add_host(host, hba->dev);
9363         if (err) {
9364                 dev_err(hba->dev, "scsi_add_host failed\n");
9365                 goto out_disable;
9366         }
9367
9368         hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9369         if (IS_ERR(hba->cmd_queue)) {
9370                 err = PTR_ERR(hba->cmd_queue);
9371                 goto out_remove_scsi_host;
9372         }
9373
9374         hba->tmf_tag_set = (struct blk_mq_tag_set) {
9375                 .nr_hw_queues   = 1,
9376                 .queue_depth    = hba->nutmrs,
9377                 .ops            = &ufshcd_tmf_ops,
9378                 .flags          = BLK_MQ_F_NO_SCHED,
9379         };
9380         err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9381         if (err < 0)
9382                 goto free_cmd_queue;
9383         hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9384         if (IS_ERR(hba->tmf_queue)) {
9385                 err = PTR_ERR(hba->tmf_queue);
9386                 goto free_tmf_tag_set;
9387         }
9388
9389         /* Reset the attached device */
9390         ufshcd_device_reset(hba);
9391
9392         ufshcd_init_crypto(hba);
9393
9394         /* Host controller enable */
9395         err = ufshcd_hba_enable(hba);
9396         if (err) {
9397                 dev_err(hba->dev, "Host controller enable failed\n");
9398                 ufshcd_print_evt_hist(hba);
9399                 ufshcd_print_host_state(hba);
9400                 goto free_tmf_queue;
9401         }
9402
9403         /*
9404          * Set the default power management level for runtime and system PM.
9405          * Default power saving mode is to keep UFS link in Hibern8 state
9406          * and UFS device in sleep state.
9407          */
9408         hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9409                                                 UFS_SLEEP_PWR_MODE,
9410                                                 UIC_LINK_HIBERN8_STATE);
9411         hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9412                                                 UFS_SLEEP_PWR_MODE,
9413                                                 UIC_LINK_HIBERN8_STATE);
9414
9415         INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9416                           ufshcd_rpm_dev_flush_recheck_work);
9417
9418         /* Set the default auto-hiberate idle timer value to 150 ms */
9419         if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9420                 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9421                             FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9422         }
9423
9424         /* Hold auto suspend until async scan completes */
9425         pm_runtime_get_sync(dev);
9426         atomic_set(&hba->scsi_block_reqs_cnt, 0);
9427         /*
9428          * We are assuming that device wasn't put in sleep/power-down
9429          * state exclusively during the boot stage before kernel.
9430          * This assumption helps avoid doing link startup twice during
9431          * ufshcd_probe_hba().
9432          */
9433         ufshcd_set_ufs_dev_active(hba);
9434
9435         async_schedule(ufshcd_async_scan, hba);
9436         ufs_sysfs_add_nodes(hba->dev);
9437
9438         return 0;
9439
9440 free_tmf_queue:
9441         blk_cleanup_queue(hba->tmf_queue);
9442 free_tmf_tag_set:
9443         blk_mq_free_tag_set(&hba->tmf_tag_set);
9444 free_cmd_queue:
9445         blk_cleanup_queue(hba->cmd_queue);
9446 out_remove_scsi_host:
9447         scsi_remove_host(hba->host);
9448 out_disable:
9449         hba->is_irq_enabled = false;
9450         ufshcd_hba_exit(hba);
9451 out_error:
9452         return err;
9453 }
9454 EXPORT_SYMBOL_GPL(ufshcd_init);
9455
9456 static int __init ufshcd_core_init(void)
9457 {
9458         ufs_debugfs_init();
9459         return 0;
9460 }
9461
9462 static void __exit ufshcd_core_exit(void)
9463 {
9464         ufs_debugfs_exit();
9465 }
9466
9467 module_init(ufshcd_core_init);
9468 module_exit(ufshcd_core_exit);
9469
9470 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9471 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9472 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9473 MODULE_LICENSE("GPL");
9474 MODULE_VERSION(UFSHCD_DRIVER_VERSION);