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