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