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