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