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